gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:38:25 27 4
gpt4 key购买 nike

假设我有一个具有 3 个返回值的函数。我设置了其中 2 个的值,如果我不设置它,我想将第 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: "all non-blank names in the signature must be unique."第一个返回参数名称 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com