Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to an unnamed function argument in go?

Tags:

go

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 ?

like image 476
user1255770 Avatar asked Jun 02 '14 17:06

user1255770


People also ask

Does Golang have anonymous functions?

Golang and the Go programming language supports anonymous functions and these anonymous functions are also known as closures.

Can Go have optional parameters?

Go doesn't support optional function parameters. This was an intentional decision by the language creators: One feature missing from Go is that it does not support default function arguments.

How do you call a function in Go lang?

Call() Function in Golang is used to calls the function v with the input arguments in. To access this function, one needs to imports the reflect package in the program. Parameters: This function takes the following parameters: in : This parameter is the []Value type.


1 Answers

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.

like image 194
julienc Avatar answered Oct 17 '22 15:10

julienc