我是 Go 编程新手,
假设此代码位于函数 fmt.Printf()
中传递两个不同的值
package main
import "fmt"
func main() {
var a int = 150
var b int = 130
var ret1, ret2 int
ret1, ret2 = max(a, b)
fmt.Printf( "Max val: %d Min val: %d\n", ret1, ret2 )
}
func max(num1, num2 int) (int,int) {
if (num1 > num2) {
return num1, num2
} else {
return num2, num1
}
}
在 fmt.Printf( "Max val: %d Min val: %d\n", ret1, ret2 )
中传递 ret2,而不是传递 ret1有什么办法可以直接传max(a, b)
在fmt.Printf()
喜欢
fmt.Printf( "Max val: %d Min val: %d\n", max(a, b))
我试过了,它给出了错误
multiple-value max() in single-value context
看来,返回两个不同的值而不是元组,是我的返回概念是错误的或者我做错了。
是否有任何方法可以将具有多个返回值的函数直接传递给需要可变数量值的函数
TIA
最佳答案
来自specification :
As a special case, if the return values 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. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters.
您想要进行的调用的问题是 Printf
的参数之一不是 max
的返回值。此调用确实有效:
fmt.Println(max(a, b))
关于go - Go lang函数返回多个值如何使用可变参数传递给其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41076250/