1

recently i decided to take a look at the context package and i feel i get the hang of it. However, in a video i saw this odd looking line of code, partly i understood it but not the last bit.

I did not include the entire code of that vidoe because i feel like its irrelevant. My question however is, what this this mean: ".(*log.Entry)". Thanks for replies, i have seen this in multiple examples but it is never explained, is it converting log which i believe is an interface{}, to *log.Entry?

func index(w http.ResponseWriter, r *http.Request {
  log, ok := r.Context().Value(logger).(*log.Entry)
  ...
  ...
}
TraineeGuy
  • 81
  • 1
  • 7

1 Answers1

3

It's a type assertion. The value obtained from r.Context().Value(logger) is an interface{}, and the type assertion checks that the underlying value is a pointer to log.Entry, and it it is, it set ok to true, and log to the value of type *log.Entry. Otherwise ok will be false (and log will be a nil of type *log.Entry).

See the language specification: https://golang.org/ref/spec#Type_assertions

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118