go - 是否可以在 Go 中的单值上下文中有选择地获取返回值?

标签 go return-value

一个简单的例子:

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 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.

除了临时变量(这是最好的选择)之外你能做的最好的是:

func first(a interface{}, _ ...interface{}) interface{} {
    return a
}

func main() {
    gimmeOnePlease(first(hereTakeTwo()).(int))
}

Playground :http://play.golang.org/p/VXv-tsYjXt

可变版本:http://play.golang.org/p/ulpdp3Hppj

关于go - 是否可以在 Go 中的单值上下文中有选择地获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27229402/

相关文章:

function - 获取不同内容 map 的所有 map 键[字符串]

go - 将 go-pg 查询转换为纯 sql

python - 如果函数满足条件而不使用额外变量,则使用函数的返回值

sql - 出错时从存储过程返回值

json - 如何仅使用消息描述符将 protobuf 线格式转换为 JSON?

angular - 在预检请求中发送自定义 header OPTIONS angular 5

java - 这个方法必须返回int类型的结果吗?

java - 为什么 Java 在通过反射调用不装箱的方法时不支持访问原始返回值?

c - 将 `log10(2)` 的结果分配给一个常量

go - 了解接口(interface)中的接口(interface)(嵌入式接口(interface))