gpt4 book ai didi

go - 如何在 go 中引用未命名的函数参数?

转载 作者:IT王子 更新时间:2023-10-29 00:40:40 26 4
gpt4 key购买 nike

go 中的函数参数名称是可选的。意味着以下是合法的

func hello(string) {

fmt.Println("Hello")
}

func main() {
hello("there")
}

( Go Playground link )

如何在foo() 函数 ?

最佳答案

未命名参数的唯一用途是当您必须定义具有特定签名的函数时。例如,我在我的一个项目中有这个例子:

type export struct {
f func(time.Time, time.Time, string) (interface{}, error)
folder string
}

我可以在其中使用这两个函数:

func ExportEvents(from, to time.Time, name string) (interface{}, error)
func ExportContacts(from, to time.Time, _ string) (interface{}, error)

即使在 ExportContacts 的情况下,我也没有使用 string 参数。事实上,如果不命名这个参数,我就没有办法在这个函数中使用它。

关于go - 如何在 go 中引用未命名的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24000305/

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