Last active
February 5, 2019 17:04
-
-
Save betandr/6ebbd1c9f1db4372352f8eebe766098e to your computer and use it in GitHub Desktop.
Pointer Receivers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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