October 2015
Beginner to intermediate
400 pages
14h 44m
English
A method is declared with a variant of the ordinary function declaration in which an extra parameter appears before the function name. The parameter attaches the function to the type of that parameter.
Let’s write our first method in a simple package for plane geometry:
package geometry
import "math"
type Point struct{ X, Y float64 }
// traditional function
func Distance(p, q Point) float64 {
return math.Hypot(q.X-p.X, q.Y-p.Y)
}
// same thing, but as a method of the Point type
func (p Point) Distance(q Point) float64 {
return math.Hypot(q.X-p.X, q.Y-p.Y)
}
The extra parameter p is called the method’s receiver, a legacy from early object-oriented languages that ...
Read now
Unlock full access