duan0403788996 2014-07-19 18:05
浏览 29
已采纳

出错-单值上下文中的多值fn()

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!")
    }
}
  • 写回答

1条回答 默认 最新

  • doumowu7371 2014-07-19 18:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)