Interface values

Under the hood, interface values can be thought of as a tuple of a value and a concrete type:

  1. (value, type)

An interface value holds a value of a specific underlying concrete type.

Calling a method on an interface value executes the method of the same name on its underlying type.

interface-values.go

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