-2

I have the following code snippet

type tracingHandler struct {
    handler http.Handler
}

var _ http.Handler = &tracingHandler{}

What is the reason for declaring a variable which is not used?

HamoriZ
  • 2,370
  • 18
  • 38

1 Answers1

2

It's a compile time check by the package developer. The package will not compile if tracingHandler does not implement the http.Handler interface.

I assume this is a middleware http package - so the developer is ensuring their handler follows the standard library's http.Handler interface:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

So, to compile, the tracingHandler type must have a method with a pointer receiver - since the assignment used &tracingHandler{} - and the method signature should look like this:

func (h * tracingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // ...
}

Using the blank identifier _ ensures the assignment is never stored and thus is a NOP. So the line is purely a build integrity check.

colm.anseo
  • 19,337
  • 4
  • 43
  • 52