This is a creation in Article, where the information may have evolved or changed.
Method
Go does not has classes. However, you can define methods on types.
Package Mainimport ("FMT" "Math") Type Vertexstruct{X, Y float64}func (v Vertex) Abs () float64 {returnMath. SQRT (v.x*v.x + v.y*v.y)} Func (v*Vertex) Scale (f float64) {v.x= v.x *F v.y= V.y *F}func (v Vertex) Scalevalue (f float64) {v.x= v.x *F v.y= V.y *F}func Main () {V:= vertex{3,4} fmt. Println (V.abs ()) V.scale (2) fmt. Println (V.abs ()) V.scalevalue (2) fmt. Println (V.abs ()) P:= &v P.scale (2) fmt. Println (P.abs ())}
The output is as follows:
5
10
10
20
Three points of note:
1. Methods with pointer receivers can modify the value to which the receiver points.
2. Methods with pointer receivers take either a value or a pointer as the receiver when they is called:
var v Vertexv.scale (5) // OKP: = &VP. Scale (ten// OK
3. Methods with value receivers take either a value or a pointer as the receiver when they is called:
var/ OKp: = &// OK
Interface
Package Mainimport ("FMT") Type IInterface{M ()}type Tstruct{Sstring}func (t*T) M () {fmt. Println (T.S)}func main () {varI i t:= t{"Hello"} i= &T I.M () V:= t{" World"} i=v I.M ()}
The second half of the code in the main function will cause an error: Cannot use V (type T) as type I in assignment:t does not implement I (M method have pointer receiver)
If you change the receiver type of M to value:
Func (T-T) M () { fmt. Println (T.S)}
The code for the main function will run normally.