Methods are functions

Remember: a method is just a function with a receiver argument.

Here's Abs written as a regular function with no change in functionality.

methods-funcs.go

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. type Vertex struct {
  7. X, Y float64
  8. }
  9. func Abs(v Vertex) float64 {
  10. return math.Sqrt(v.X*v.X + v.Y*v.Y)
  11. }
  12. func main() {
  13. v := Vertex{3, 4}
  14. fmt.Println(Abs(v))
  15. }