This is a creation in Article, where the information may have evolved or changed.
The definition of a struct is simple:
Type Vertex struct { X, Y float64}
Can be understood as a collection of multiple variables.
Use of the structure:
1. Direct use:
V: = vertex{1, 2}
Or
var v = vertex{1, 2}
2. Through the New keyword:
New (Vertex)
3. Access by pointers:
V: = &vertex{1, 2}
To add a method to a struct:
Package Main Import ( "FMT" "math") type Vertex struct { *Vertex) scale (f float64) { = v.x * F = V.Y **Vertex) Abs () float64 { return math. SQRT (v.x*v.x + v.y*v.y)}func main () { V:= &vertex{3, 4} V.scale (5) FMT . Println (V, V.abs ())}
Adding a method to a struct is to add a pointer reference (or a value reference) to the struct by adding a parenthesis between the Func and the method name when defining the method.
What is notable here is the difference between a pointer reference and a value reference:
Pointer references can modify the structure's internal data, while value references cannot, as in the following example:
PackageMainImport ( "FMT") type Vertex struct {X, Yint}//Value Referencefunc (v Vertex) show () {v.x= 1}//Pointer ReferenceFunc (v *Vertex) Show1 () {v.x= 1}func Main () {V:= &vertex{3, 4} v.show () fmt. Println (v.x)//Output: 3V.show1 () fmt. Println (v.x)//Output: 1}
You can see that if you do not use a pointer reference in the method definition of a struct, you cannot change the value of the member variable of the struct body.
Summary: Golang is a non-object-oriented language, for writing Java more than I am still a bit difficult to accept, maybe C students more acceptable. If you are not comparing, you can say that the structure of the go language is similar to the class in Java, but obviously lacks the inheritance polymorphism and so on oo characteristics.
In addition, the pointer in go compared to the C-system language seems to be castrated version, that is, only when the variable declaration is used, does not involve the pointer operation, although it is strange but this still reduces the language difficulty ha.