packagegeometryimport"math"typePointstruct{X,Yfloat64}// traditional functionfuncDistance(p,qPoint)float64{returnmath.Hypot(q.X-p.X,q.Y-p.Y)}// same thing, but as a method of the Point typefunc(p Point)Distance(qPoint)float64{returnmath.Hypot(q.X-p.X,q.Y-p.Y)}
p := Point{1, 2}
q := Point{4, 6}
fmt.Println(Distance(p, q)) // "5", function call
fmt.Println(p.Distance(q)) // "5", method call
// A Path is a journey connecting the points with straight lines.
type Path []Point
// Distance returns the distance traveled along the path.
func (path Path) Distance() float64 {
sum := 0.0
for i := range path {
if i > 0 {
sum += path[i-1].Distance(path[i])
}
}
return sum
}