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")
}
_(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.
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.
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
.
_ 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With