How do you return two values from a single method?

后端 未结 22 850
谎友^
谎友^ 2020-12-11 00:58

When your in a situation where you need to return two things in a single method, what is the best approach?

I understand the philosophy that a method should do one t

22条回答
  •  孤城傲影
    2020-12-11 01:59

    This is not entirely language-agnostic: in Lisp, you can actually return any number of values from a function, including (but not limited to) none, one, two, ...

    (defun returns-two-values ()
      (values 1 2))
    

    The same thing holds for Scheme and Dylan. In Python, I would actually use a tuple containing 2 values like

    def returns_two_values():
       return (1, 2)
    

    As others have pointed out, you can return multiple values using the out parameters in C#. In C++, you would use references.

    void 
    returns_two_values(int& v1, int& v2)
    {
        v1 = 1; v2 = 2;
    }
    

    In C, your method would take pointers to locations, where your function should store the result values.

    void 
    returns_two_values(int* v1, int* v2)
    {
        *v1 = 1; *v2 = 2;
    }
    

    For Java, I usually use either a dedicated class, or a pretty generic little helper (currently, there are two in my private "commons" library: Pair and Triple, both nothing more than simple immutable containers for 2 resp. 3 values)

提交回复
热议问题