13

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")
}
Camilo Crespo
  • 615
  • 5
  • 15
  • 1
    Related questions: 1. [Getting method parameter names in Golang](http://stackoverflow.com/questions/31377433/getting-method-parameter-names-in-golang); 2. [Why does Go allow compilation of unused function parameters?](http://stackoverflow.com/questions/22549228/why-does-go-allow-compilation-of-unused-function-parameters) – icza May 06 '16 at 22:03

4 Answers4

16

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.

Gary Sham
  • 503
  • 4
  • 10
9

_ 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.

matt.s
  • 1,698
  • 1
  • 20
  • 29
2

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".

Ross Albertson
  • 101
  • 1
  • 5
0

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.=.

0x0
  • 2,915
  • 5
  • 40
  • 67