go - 单值上下文错误中的多值返回变量和多返回函数

标签 go

我试图返回一个变量以及一个返回多个值的函数。

考虑这个人为的例子:

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

有三种方法可以从具有结果类型的函数返回值:

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

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

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

相关文章:

go - 为什么 byte cast 炸毁不一致的 golang?

multithreading - 简单队列模型示例

docker - 在不调用 go build 的情况下为 golang 应用程序构建 docker 容器

go - 在 Go 中如何遍历指针列表?

go - Chromedp 包 : How to get updated HTML source of the webpage which has dynamically loaded contents by using chromedp

c - Ocaml-> .so-> Golang

go - 调用包的函数而不使用其包名称?

git - 通过代理进行go-git克隆

go - 为什么 golang duck typing 在我下面的代码中对我不起作用?

go - 修改hugo中的index.html