Interfaces

An interface type is defined as a set of method signatures.

A value of interface type can hold any value that implements those methods.

Note: There is an error in the example code on line 22. Vertex (the value type) doesn't implement Abser because the Abs method is defined only on *Vertex (the pointer type).

interfaces.go

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. type Abser interface {
  7. Abs() float64
  8. }
  9. func main() {
  10. var a Abser
  11. f := MyFloat(-math.Sqrt2)
  12. v := Vertex{3, 4}
  13. a = f // a MyFloat implements Abser
  14. a = &v // a *Vertex implements Abser
  15. // In the following line, v is a Vertex (not *Vertex)
  16. // and does NOT implement Abser.
  17. a = v
  18. fmt.Println(a.Abs())
  19. }
  20. type MyFloat float64
  21. func (f MyFloat) Abs() float64 {
  22. if f < 0 {
  23. return float64(-f)
  24. }
  25. return float64(f)
  26. }
  27. type Vertex struct {
  28. X, Y float64
  29. }
  30. func (v *Vertex) Abs() float64 {
  31. return math.Sqrt(v.X*v.X + v.Y*v.Y)
  32. }