go - 部分使用命名结果参数来设置默认值

标签 go

假设我有一个有 3 个返回值的函数。我设置了其中两个的值,如果不设置,则希望将第三个保留为默认值。像这样的东西 -

func call(a int) (int, int, r3 string){

  //        return a, a+1, "no error" // stmt 1
  //        return a, a+1             // stmt 2
  //        return                    // stmt 3
}

在未注释的 stmt 2 或 stmt 3 下运行,出现以下错误 -

duplicate argument int
int is shadowed during return

这里 int 是如何被隐藏的?返回列表没有命名 int 参数。

在 stmt 1 未注释的情况下运行,出现以下错误 -

duplicate argument int
cannot use a (type int) as type string in return argument
cannot use a + 1 (type int) as type string in return argument

有人可以解释这些错误的根源吗?

是否不可能拥有命名结果参数的部分列表(甚至在使用命名结果参数时返回变量)?

最佳答案

The Go Programming Language Specification

Function types

Within a list of parameters or results, the names (IdentifierList) must either all be present or all be absent. If present, each name stands for one item (parameter or result) of the specified type and all non-blank names in the signature must be unique. If absent, each type stands for one item of that type.


package main

// duplicate argument int
func call1(a int) (int, int, r3 string) {
    // int is shadowed during return
    return
}

// duplicate argument int
func call2(a int) (int string, int string, r3 string) {
    // int is shadowed during return
    return
}

// duplicate argument int
func call3(a bool) (int, int, r3 string) {
    // int is shadowed during return
    return
}

func call4(a int) (int, r2, r3 string) {
    return
}

func call5(a int) (r1, r2, r3 string) {
    return
}

func main() {}

Playground :https://play.golang.org/p/PUhY7Y0H9f

输出:

tmp/sandbox842451638/main.go:4:33: duplicate argument int
tmp/sandbox842451638/main.go:6:2: int is shadowed during return
tmp/sandbox842451638/main.go:10:47: duplicate argument int
tmp/sandbox842451638/main.go:12:2: int is shadowed during return
tmp/sandbox842451638/main.go:16:34: duplicate argument int
tmp/sandbox842451638/main.go:18:2: int is shadowed during return

call1call2 的简写。正如您所看到的,您有重复的返回参数名称int:“签名中的所有非空白名称必须是唯一的。”第一个返回参数名称 int 被第二个返回参数名称 int 遮盖。


如果您想要匿名返回参数,可以使用空白标识符。

package main

// duplicate argument int
func callA(a int) (int, int, r3 string) {
    // int is shadowed during return
    return
}

func callB(a int) (_ int, _ int, r3 string) {
    return
}

func main() {}

Playground :https://play.golang.org/p/CS1x9mmIh6

关于go - 部分使用命名结果参数来设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47506173/

相关文章:

mongodb - mgo 中的关系

json - 如何解码json数据 Go

go - 内存中的数据以最小化数据库读取?

clojure - 多机分布式Clojure的现状?

go - 普罗米修斯自定义注册表不工作

go client watch etcd 事件失败

go - Go 中来自 Kubernetes 的 Cloud SQL 连接 - 错误 403 : Insufficient Permission

go - 多个客户端之间的并发数据中继

Golang 浮点运算

戈朗 : how to explain the type assertion efficiency?