简体   繁体   English

go error - 单值上下文中的多值 fn()

[英]go error - multiple-value fn() in single-value context

I want to pass the results from a function fn() returning multiple values into a function wantx() that accepts multiple values.我想将返回多个值的函数 fn() 的结果传递给接受多个值的函数 wantx() 。 This seems to work if the number of values accepted by wantx() matches the number of return values.如果 wantx() 接受的值数量与返回值的数量匹配,这似乎有效。 For example, fn() returns 2 values, and want2() accepts 2 values:例如, fn() 返回 2 个值,而 want2() 接受 2 个值:

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:但是,如果我希望 fn() 的返回值充当 want3() 的参数 2 和 3,则会出现错误:

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

How is want2() a multiple-value context while want3() is not ? want2() 如何成为多值上下文,而 want3() 不是?

How do I get the call to want3() to work ?我如何获得对 want3() 的调用?

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!")
    }
}

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.作为一种特殊情况,如果函数或方法 g 的返回参数数量相等并且可以单独分配给另一个函数或方法 f 的参数,那么调用 f(g(parameters_of_g)) 将在绑定返回值后调用 f g 到 f 的参数的顺序。

No other special cases for function calls are allowed.不允许函数调用的其他特殊情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM