Let's say I have a function with 3 return values. I set the values of 2 of them, and want to leave the 3rd one to default if I do not set it. Something like this -
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
}
Running with stmt 2 or stmt 3 uncommented, I get below error -
duplicate argument int
int is shadowed during return
How is int shadowed here? The return list does not have named int params.
Running with stmt 1 uncommented, I get below error -
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
Can someone explain origin of these errors ?
Is it not possible to have partial list of named result params (or even returning variables when using named result params) ?
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
Output:
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
is shorthand for call2
. As you can see, you have duplicate return argument names int
: "all non-blank names in the signature must be unique." The first return argument name int
is shadowed by the second return argument name int
.
If you want anonymous return arguments, you can use the blank identifier.
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