Methods

Go+ does not have classes. However, you can define methods on types. A method is a function with a special receiver argument. The receiver appears in its own argument list between the func keyword and the method name.

import ( "math" ) type Vertex struct { X, Y float64 } func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } v := Vertex{3, 4} println(v.Abs())

Declare a method on non-struct types

import ( "math" ) type MyFloat float64 func (f MyFloat) Abs() float64 { if f < 0 { return float64(-f) } return float64(f) } f := MyFloat(-math.Sqrt2) println(f.Abs())

In this example we see a numeric type MyFloat with an Abs method. You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package (which includes the built-in types such as int).

Next example: Methods with a Pointer Receiver