Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of underscore in a Go function parameter

Tags:

go

Came accross the below function here. I noticed the last parameter is identified with _. What is the intent of this pattern?

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}
like image 244
Camilo Crespo Avatar asked May 06 '16 19:05

Camilo Crespo


People also ask

What does underscore mean in go?

_(underscore) in Golang is known as the Blank Identifier. Identifiers are the user-defined name of the program components used for the identification purpose. Golang has a special feature to define and use the unused variable using Blank Identifier.

How do you write a function in Golang?

In Golang, we declare a function using the func keyword. A function has a name, a list of comma-separated input parameters along with their types, the result type(s), and a body. The input parameters and return type(s) are optional for a function. A function can be declared without any input and output.


2 Answers

It means "ignore that parameter", the reason that they still need the last parameter here is because they want to pass it as type Handle to the function GET, which has the signature:

type Handle func(http.ResponseWriter, *http.Request, Params)

If you simply pass something like func Index(w http.ResponseWriter, r *http.Request) it will not be treated as type Handle.

like image 71
Gary Sham Avatar answered Oct 20 '22 17:10

Gary Sham


_ is the blank identifier. It's in the signature to show that the value doesn't get used, so the signature will still match the methods of the interface.

like image 22
matt.s Avatar answered Oct 20 '22 18:10

matt.s