Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

go error - multiple-value fn() in single-value context

Tags:

go

I want to pass the results from a function fn() returning multiple values into a function wantx() that accepts multiple values. This seems to work if the number of values accepted by wantx() matches the number of return values. For example, fn() returns 2 values, and want2() accepts 2 values:

r:= want2( fn(5) )   // seems to work fine

However, if I want the return values of fn() to act as arguments 2 and 3 of want3(), then I get an error:

r:= want3( 1, fn(5) ) // error: multiple-value fn() in single-value context

How is want2() a multiple-value context while want3() is not ?

How do I get the call to want3() to work ?

Here is the full program:

package sandbox

import "testing"

func want3(fac int, i int, ok bool) int {
    if ok {
        return i * fac * 2
    }
    return i * fac * 3
}

func want2(i int, ok bool) int {
    if ok {
        return i * 2
    }
    return i * 3
}

func fn(i int) (int, bool) {
    return i, true
}

func TestCall(t *testing.T) {
    // error: multiple-value fn() in single-value context
    // r := want3(1, fn(5))

    r := want2( fn(5) )  // works fine

    if r != 10 {
        t.Errorf("Call!")
    }
}
like image 929
Martin Avatar asked Jul 19 '14 18:07

Martin


1 Answers

See here:

As a special case, if the return parameters of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order.

No other special cases for function calls are allowed.

like image 58
0xAX Avatar answered Nov 13 '22 13:11

0xAX