interface_nil.go 965 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // interface_nil.go
  2. package main
  3. import "fmt"
  4. type Any interface{}
  5. type Anything struct{}
  6. func main() {
  7. any := getAny()
  8. if any == nil {
  9. fmt.Println("any is nil")
  10. } else {
  11. fmt.Println("any is not nil")
  12. }
  13. /*
  14. // to get the inner value:
  15. anything := any.(*Anything)
  16. if anything == nil {
  17. fmt.Println("anything is nil")
  18. } else {
  19. fmt.Println("anything is not nil")
  20. }
  21. */
  22. }
  23. func getAny() Any {
  24. return getAnything()
  25. }
  26. func getAnything() *Anything {
  27. return nil
  28. }
  29. /* Output:
  30. any is not nil
  31. WHY?
  32. you would perhaps expect: any is nil,because getAnything() returns that
  33. BUT:
  34. the interface value any is storing a value, so it is not nil.
  35. It just so happens that the particular value it is storing is a nil pointer.
  36. The any variable has a type, so it's not a nil interface,
  37. rather an interface variable with type Any and concrete value (*Anything)(nil).
  38. To get the inner value of any, use: anything := any.(*Anything)
  39. now anything contains nil !
  40. */