How to refer to an unnamed function argument in go?

huangapple go评论87阅读模式
英文:

How to refer to an unnamed function argument in go?

问题

在Go语言中,函数参数的名称是可选的,这意味着以下代码是合法的:

func hello(string) {
    fmt.Println("Hello")
}

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

如果你想在foo()函数中引用第一个参数(声明为string类型的参数),你可以使用下划线 _ 来忽略参数名称。以下是示例代码:

func foo(arg1 string) {
    fmt.Println(arg1)
}

你可以在foo()函数中使用arg1来引用第一个参数。

英文:

The name of a function parameter in go is optional. meaning the following is legal

func hello(string) {

    fmt.Println("Hello")
}

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

(Go Playground link)

How can I refer to the 1. argument (declared with a type of string) argument in the
foo() function ?

答案1

得分: 11

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

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参数。实际上,如果不给该参数命名,我无法在这个函数中使用它。

英文:

The only use of unnamed parameters is when you have to define a function with a specific signature. For instance, I have this example in one of my projects:

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

And I can use both of these functions in it:

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

Even though in the case of ExportContacts, I do not use the string parameter. In fact, without naming this parameter, I have no way of using it in this function.

huangapple
  • 本文由 发表于 2014年6月3日 01:43:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/24000305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定