Interface values with nil underlying values

If the concrete value inside the interface itself is nil, the method will be called with a nil receiver.

In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.)

Note that an interface value that holds a nil concrete value is itself non-nil.

interface-values-with-nil.go

  1. package main
  2. import "fmt"
  3. type I interface {
  4. M()
  5. }
  6. type T struct {
  7. S string
  8. }
  9. func (t *T) M() {
  10. if t == nil {
  11. fmt.Println("")
  12. return
  13. }
  14. fmt.Println(t.S)
  15. }
  16. func main() {
  17. var i I
  18. var t *T
  19. i = t
  20. describe(i)
  21. i.M()
  22. i = &T{"hello"}
  23. describe(i)
  24. i.M()
  25. }
  26. func describe(i I) {
  27. fmt.Printf("(%v, %T)\n", i, i)
  28. }