我试图返回一个变量以及一个返回多个值的函数。
考虑这个人为的例子:
func twoInts() (int, int) {
return 2, 3
}
func threeInts() (int, int, int) {
return 1, twoInts()
}
调用threeInts()返回“单值上下文中的多值twoInts()”。
我了解我可以执行以下操作
func twoInts() (int, int) {
return 2, 3
}
func threeInts() (int, int, int) {
num1, num2 := twoInts()
return 1, num1, num2
}
但我试图理解为什么返回值是单值上下文。
Go认为返回是
int, (int, int)
?有没有办法扩展第一个函数的返回值,使其返回int, int, int
?
最佳答案
https://golang.org/ref/spec#Return_statements
有三种方法可以从具有结果类型的函数返回值:
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.
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.
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.
这三种方式均不允许将单值表达式与对多值函数的调用混合使用。
“有没有办法扩展第一个函数的返回值,使其返回int,int,int?”不,没有。
关于go - 单值上下文错误中的多值返回变量和多返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57908601/