Pointers and functions

Here we see the Abs and Scale methods rewritten as functions.

Again, try removing the * from line 16. Can you see why the behavior changes? What else did you need to change for the example to compile?

(If you're not sure, continue to the next page.)

methods-pointers-explained.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 Scale(v *Vertex, f float64) {
  13. v.X = v.X * f
  14. v.Y = v.Y * f
  15. }
  16. func main() {
  17. v := Vertex{3, 4}
  18. Scale(&v, 10)
  19. fmt.Println(Abs(v))
  20. }