duanmoen784988 2019-09-12 14:10
浏览 31
已采纳

单值上下文错误中的多值返回变量和多返回函数

I'm trying to return a variable along with a function that returns multiple values.

Consider this contrived example:

func twoInts() (int, int) {
    return 2, 3
}
func threeInts() (int, int, int) {
    return 1, twoInts()
}

Calling threeInts() returns "multiple-value twoInts() in single-value context".

I understand I can do the following

func twoInts() (int, int) {
    return 2, 3
}
func threeInts() (int, int, int) {
    num1, num2 := twoInts()
    return 1, num1, num2
}

but I am trying to understand why the return is a single-value context.

Does Go consider the return to be int, (int, int)? Is there a way to expand the first function return so that it does return int, int, int?

  • 写回答

2条回答 默认 最新

  • ds342222222 2019-09-12 14:20
    关注

    https://golang.org/ref/spec#Return_statements

    There are three ways to return values from a function with a result type:

    1. The return value or values may be explicitly listed in the "return" statement. Each expression must be single-valued and assignable to the corresponding element of the function's result type.

    2. The expression list in the "return" statement may be a single call to a multi-valued function. The effect is as if each value returned from that function were assigned to a temporary variable with the type of the respective value, followed by a "return" statement listing these variables, at which point the rules of the previous case apply.

    3. The expression list may be empty if the function's result type specifies names for its result parameters. The result parameters act as ordinary local variables and the function may assign values to them as necessary. The "return" statement returns the values of these variables.

    None of the 3 ways allow mixing single-value expressions with a call to a multi-valued function.


    "Is there a way to expand the first function return so that it does return int, int, int?" No, there isn't.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂