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")
}
How can I refer to the 1. argument (declared with a type of string) argument in the foo() function ?
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.