假设我有一个有 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
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
call1
是 call2
的简写。正如您所看到的,您有重复的返回参数名称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/