Go does not have classes. However, you can define methods on types.函數
package main import ( "fmt" "math" ) type Vertex struct { X, Y float64 } func (v Vertex) Abs() float64 { return math.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()) }
輸出以下:spa
5
10
10
20code
1. Methods with pointer receivers can modify the value to which the receiver points 。blog
2. methods with pointer receivers take either a value or a pointer as the receiver when they are called:string
var v Vertex v.Scale(5) // OK p := &v p.Scale(10) // OK
3. methods with value receivers take either a value or a pointer as the receiver when they are called:it
var v Vertex fmt.Println(v.Abs()) // OK p := &v fmt.Println(p.Abs()) // OK
package main import ( "fmt" ) type I interface { M() } type T struct { S string } func (t *T) M() { fmt.Println(t.S) } func main() { var i I t := T{"hello"} i = &t i.M() v := T{"world"} i = v i.M() }
main函數後半段代碼會報錯:cannot use v (type T) as type I in assignment: T does not implement I (M method has pointer receiver)class
若是把M的receiver類型改爲value:import
func (t T) M() { fmt.Println(t.S) }
main函數的代碼將正常運行。float