英文:
go error - multiple-value fn() in single-value context
问题
我想将返回多个值的函数fn()的结果传递给接受多个值的函数wantx()。如果wantx()接受的值的数量与返回值的数量相匹配,似乎可以正常工作。例如,fn()返回2个值,而want2()接受2个值:
r := want2(fn(5)) // 似乎可以正常工作
然而,如果我希望fn()的返回值作为want3()的第2个和第3个参数,那么就会出现错误:
r := want3(1, fn(5)) // 错误:在单值上下文中使用多值fn()
为什么want2()是多值上下文而want3()不是?
如何使调用want3()正常工作?
以下是完整的程序:
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) {
// 错误:在单值上下文中使用多值fn()
// r := want3(1, fn(5))
r := want2(fn(5)) // 正常工作
if r != 10 {
t.Errorf("Call!")
}
}
英文:
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
得分: 9
请看这里:
> 作为一个特殊情况,如果函数或方法 g 的返回参数的数量与另一个函数或方法 f 的参数数量相等,并且可以逐个赋值给 f 的参数,则调用 f(g(parameters_of_g)) 将在绑定 g 的返回值到 f 的参数后按顺序调用 f。
>
> 不允许其他函数调用的特殊情况。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论