Method
Go has no class. However, you can still define a method on a struct type.
The method recipient appears in the argument between the Func keyword and the method name.
Case a----object
Package main
Import (
"FMT"
"math"
)
type Vertex struct {
X, Y float64
}
func (v * Vertex) Abs () float64 {//pointer type return
math. SQRT (v.x*v.x + v.y*v.y)
}
func main () {
V: = &vertex{3, 4}
FMT. Println (V.abs ())
}
Case two----common type
Package main
Import (
"FMT"
"math"
)
type myfloat float64
func (f myfloat) Abs () float64 {//value type
if f < 0 {return
float64 (-f)
} return
float64 (f)}
func main () {
f: = MYFL Oat (-math. SQRT2)
FMT. Println (F.abs ())
}
this defines 2 methods of passing type parameters, one on the *vertex pointer type and the other on the Myfloat value type. The difference is as follows
1. Values passed by value type are only useful on the current method
2. The pointer type is passed a memory address, so when any parameter value in the structure is modified in the method, it is directly stored in the structure.
Case:
Package main
Import (
"FMT"
"math"
)
type Vertex struct {
X, Y float64
}
func (v * Vertex) Scale (f float64) {
v.x = v.x * F
v.y = V.y * F
}
func (v *vertex) Abs () float64 {
return Math. SQRT (v.x*v.x + v.y*v.y)
}
func main () {
V: = &vertex{3, 4}
FMT. Printf ("Before scaling:%+v, Abs:%v\n", V, V.abs ())
V.scale (5)
A method for modifying the value of a struct parameter is called here, and when the method associated with V *vertex is the pointer type, the value of the object in V will be changed and the resulting ABS method output is 25.
//If we remove the pointer * number, the Vertex associated with this method is actually a copy of the &vertex{3, 4}
At this point in the scale method to modify the value of the object is not effective, it can not be passed to the back of the ABS method, at this time the return of the ABS results are still 5
FMT. Printf ("After scaling:%+v, Abs:%v\n", V, V.abs ())
}