Skip to content

Instantly share code, notes, and snippets.

@betandr
Last active February 5, 2019 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betandr/6ebbd1c9f1db4372352f8eebe766098e to your computer and use it in GitHub Desktop.
Save betandr/6ebbd1c9f1db4372352f8eebe766098e to your computer and use it in GitHub Desktop.
Pointer Receivers
package main
import (
"fmt"
"math"
)
type Point struct {
X, Y float64
}
func (p Point) Distance(q Point) float64 {
return math.Hypot(q.X-p.X, q.Y-p.Y)
}
func (p *Point) ScaleBy(factor float64) {
p.X *= factor
p.Y *= factor
}
func main() {
r := &Point{1, 2}
r.ScaleBy(2)
fmt.Println(*r)
p := Point{1, 2}
pptr := &p
pptr.ScaleBy(2) // is implicitly:
(*pptr).ScaleBy(2)
fmt.Println(p)
q := Point{1, 2}
q.ScaleBy(2) // is implicitly:
(&q).ScaleBy(2)
fmt.Println(q)
s := Point{1, 2}.Distance(q)
fmt.Println(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment