This is a creation in
Article, where the information may have evolved or changed.
Familiar with the syntax structure of Go function
Because go does not have a class concept, it uses structs to simulate. The functions in the code calculate the square root of the two integers and the absolute value of the values respectively.
Package Mainimport ("FMT" "math") type myfloat float64type Vertex struct {X, Y Float64}//vertex pointer corresponding abs method func (v *vertex) Ab S () float64 {return math. SQRT (v.x*v.x + v.y*v.y)}//myfloat structural Body corresponding ABS method func (F Myfloat) abs () Float64 {if f < 0 {return float64 (-f)}return float64 (f)} Func Main () {V: = &vertex{6, 4}//gets pointer to Vertex struct FMT.PRINTLN (V.abs ()) F: = Myfloat (-math. SQRT2)//Take 2 square root FMT. Println ("Float abs=", F.abs ())}
The significance of defining the corresponding method here is to manipulate the original object. If you define a method that corresponds to a struct type, the passed argument is a copy of the struct, not the original object. We can add a method as follows:
Package Mainimport ("FMT" "math") type myfloat float64type Vertex struct {X, Y Float64}//vertex pointer corresponding abs method func (v *vertex) Ab S () float64 {return math. SQRT (v.x*v.x + v.y*v.y)}//vertex pointer corresponds to the Add method func (v *vertex) Add (f float64) {v.x = FV. Y + = f}//myfloat Structure corresponding ABS method func (F Myfloat) abs () Float64 {if f < 0 {return float64 (-f)}return float64 (f)}func main () { V: = &vertex{6, 4}//gets pointer to Vertex struct FMT.PRINTLN (V.abs ()) V.add (3.14) fmt. Println (v) F: = Myfloat (-math. SQRT2)//Take 2 square root FMT. Println ("Float abs=", F.abs ())}
After running, the values of x and y inside the object v have been changed.