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")
}
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")
}
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.
Using "_" in place of a parameter name fulfills the obligations of a higher-level "function as a parameter" without getting a warning about an unused parameter. In your case, I believe the compiler is told to ignore all incoming "POST" data, thus in effect reducing the request to the functionality of a "GET".
As others pointed out, it is a blank identifier. For instance, consider the following example:
func main() {
nums := []int{5, 3, 4}
max := nums[0]
for _, num := range nums {
if num > max {
max = num
}
}
fmt.Println("max:", max)
}
If you aren't going to use an index value, you can just ignore storing it by using _
instead of a variable name.=.