一个简单的例子:
package main
import "fmt"
func hereTakeTwo() (x, y int) {
x = 0
y = 1
return
}
func gimmeOnePlease(x int){
fmt.Println(x)
}
func main() {
gimmeOnePlease(hereTakeTwo()) // fix me
}
是否可以只传递从 hereTakeTwo()
而不 使用显式 _
赋值的第一个返回值?我想避免的示例:
func main() {
okJustOne, _ := hereTakeTwo()
gimmeOnePlease(okJustOne)
}
我想要的是让 gimmeOnePlease
函数能够接收未定义数量的参数,但只接受第一个参数 OR 调用 hereTakeTwo
函数并仅获取第一个返回值,而无需使用 _
赋值。
或者在不得已的情况下(疯狂的想法)使用某种适配器函数,它接受 N 个参数并只返回第一个参数,并且有类似的东西:
func main() {
gimmeOnePlease(adapter(hereTakeTwo()))
}
为什么?我只是在测试语言的边界并了解它在某些用途上的灵 active 。
最佳答案
不,除了一种特殊情况,你不能这样做 described在规范中:
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 methodf
, then the callf(g(parameters_of_g))
will invokef
after binding the return values ofg
to the parameters off
in order. The call off
must contain no parameters other than the call ofg
, andg
must have at least one return value.
除了临时变量(这是最好的选择)之外你能做的最好的是:
func first(a interface{}, _ ...interface{}) interface{} {
return a
}
func main() {
gimmeOnePlease(first(hereTakeTwo()).(int))
}
Playground :http://play.golang.org/p/VXv-tsYjXt
关于go - 是否可以在 Go 中的单值上下文中有选择地获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27229402/