Play the struct structure of Golang

Source: Internet
Author: User

Let's introduce the type system of the Go language

Type systems in the Golang

Type system refers to the type architecture of a language. A typical type system typically contains the following basic elements:

Basic types, such as Byte, int, bool, float, etc.;
Composite types, such as arrays, structures, pointers, etc.;
Can point to the type of any object (any type);
Value semantics and referential semantics;
Object-oriented, that is, all types with object-oriented features (such as member methods);
Interface.

Most types in the go language are value semantics and can contain corresponding action methods. You can "add" new methods to any type (including built-in types) when needed. When implementing an interface, it is not necessary to inherit from the interface (in fact, the go language does not support the inheritance syntax in object-oriented thinking at all), it only needs to implement all the methods required by that interface. Any type can be referenced by any type. The any type is an empty interface, or interface{}.

What is a structural body?

A struct (struct) is a user-defined type that represents a collection of several fields that can be used to describe an entity object, similar to class in Java, and is the underlying type of Golang object-oriented programming.
The concept of a struct is an old term in software engineering called ADT (abstract data type: abstractly, datatype). In C + + It also exists, and the name is also a struct, in an object-oriented programming language, as with a lightweight class without methods. Because there is no concept of class in the go language, the structure in go has a more important position.

How to define a struct

type Coordinate struct {    X, Y float32}

Grammar:type<Name>struct{}
The code above defines a struct named, containing Coordinate two float32 variables, which X Y can be used to represent a planar coordinate.

Add Object method

Other classic object-oriented languages such as java,c#, which define object methods, are included in the definition of class, such as

public class Coordinate{    public float X {get; set;}    public float Y {get; set;}    //打印坐标    public void GetCoordinate(){          Console.WriteLine("("+this.X+","+this.Y+")");    }}

In the Go language, object methods are added outside the structure definition

type Coordinate struct {    X, Y float32}//打印坐标func (coo *Coordinate) GetCoordinate() {    fmt.Printf("(%.2f,%.2f)\n", coo.X, coo.Y)    return}

Where, func after the keyword (coo *Coordinate) , indicates that the function passed in a pointer to Coordinate the pointer variable coo to manipulate the value of the struct body.

Initialization of several structure bodies

First, by creating the structure by the original field order

package mainimport (    "fmt")func main(){    p0 := Coordinate{1, 2}    p0.GetCoordinate()}

Output: (1.00,2.00) , where x=1,y=2

Second, initialize according to the custom field order

package mainimport (    "fmt")func main(){    p0 := Coordinate{Y:1, X:2}    p0.GetCoordinate()}

Output: (2.00,1.00) , where X=2,y=1

Third, create through the new function

package mainimport (    "fmt")func main(){    //给该结构体p2变量分配内存,它返回指向已分配内存的指针    p0 := new(Coordinate)    p0.X=1    p0.Y=2    p0.GetCoordinate()}

Output: (1.00,2.00) , where x=1,y=2
Which is p0 := new(Coordinate) equivalent to the following notation

p3 := &Coordinate{X: 1, Y: 2}
p3 := &Coordinate{1,2}

Compare three ways to create

Where the first and second types p0 are instances of one type, Coordinate and the third p0 is a Coordinate pointer to, equivalent tovar p0 *Coordinate = new(Coordinate)

Typically type T struct {a, b int} after the definition of a struct for example
Used t := new(T) to allocate memory to the struct variable, which returns a pointer to the allocated memory. A variable t is a T pointer to a struct field whose value is the 0 value of the type to which they belong.
var t Tthe declaration also t allocates memory, and 0 values the memory, but at this time t is the type T. In both of these ways, T is often called an instance or an object of type T (instance) (Object) . var t *T = new(T)equivalent to t := new(T) .

Analyze the above conclusions through code

package mainimport (    "fmt")func main(){    p0 := Coordinate{1, 2}    //给该结构体p2变量分配内存,它返回指向已分配内存的指针    p2 := new(Coordinate)    p2.X = 1    p2.Y = 2    p3 := &Coordinate{X: 1, Y: 2}    p4 := &Coordinate{1, 2}    fmt.Println("-------输出p0-------")    fmt.Printf("%v\n%T\n", p0, p0)    fmt.Println("-------输出p2-------")    fmt.Printf("%v\n%T\n", p2, p2)    fmt.Println("-------输出p3-------")    fmt.Printf("%v\n%T\n", p3, p3)    fmt.Println("-------输出p4-------")    fmt.Printf("%v\n%T\n", p4, p4)}

输出:

-------输出p0-------{1 2}Coordinate-------输出p2-------&{1 2}*Coordinate-------输出p3-------&{1 2}*Coordinate-------输出p4-------&{1 2}*Coordinate

As you can see, p2,p3,p4 are a pointer variable

Object methods for adding value copies

Just now, add an object method, which can be func (t *T) functionname() created by t a pointer variable. We can also add an object method by means of a value copy, and the syntax isfunc(t T) functionname()

package mainimport (    "fmt")type Coordinate struct {    X, Y float32}func (coo *Coordinate) GetCoordinate() {    fmt.Printf("(%.2f,%.2f)\n", coo.X, coo.Y)    return}//值拷贝对象方法func (coo Coordinate) SetPosition01(a float32,b float32) {    coo.X = a    coo.Y = b}//指针变量对象方法func (coo *Coordinate) SetPosition02(a float32,b float32) {    coo.X = a    coo.Y = b}func main(){    p0 := Coordinate{1, 2}    fmt.Print("SetPosition02调用前:")    p0.GetCoordinate()    p0.SetPosition02(0, 0)    fmt.Print("SetPosition02调用后:")    p0.GetCoordinate()}

输出:

SetPosition01调用前:(1.00,2.00)SetPosition01调用后:(1.00,2.00)SetPosition02调用前:(1.00,2.00)SetPosition02调用后:(0.00,0.00)

As can be seen from the program output, the call SetPosition01 method, a value copy occurred, even if the value changed within the method coo , the external p0 value has not been changed. SetPosition02in the method, the coo pointer to p0 the address, because it is modified by the pointer variable X,Y value, so after completion of the call, p0 the external value will be revised to(0,0)

anonymous struct

package mainimport (    "fmt")func main(){    p_3d := struct {        X, Y, Z float32    }{1, 2, 3}    fmt.Println("-------输出p_3d-------")    fmt.Printf("%v\n%T\n", p_3d, p_3d)}

输出:

-------输出p_3d-------{1 2 3}struct { X float32; Y float32; Z float32 }

p_3dAs an X,Y,Z anonymous struct with three variables

Golang constructor function?

There is no concept of constructors in the go language, and the creation of objects is usually done by a global creation function that is NewXXX named "Constructors":
It's all very natural, and developers don't need to analyze how much is going on behind the scenes after using new. In the go language, everything that's going to happen is directly visible.
--"Go language Programming"

func NewRect(x, y, width, height float64) *Rect {     return &Rect{x, y, width, height}}

Variable, method visibility

The go language adds a lot of keywords to the keyword, and there private protected 's no such keyword public . To make a symbol package visible (that is, accessible) to other packages, you need to define the symbol to start with an uppercase letter, such as:

 type Rect struct {   X, Y float64  Width, Height float64 }

In this way, the member variables of the RECT type are all exported and can be accessed by all other code referencing the package where the RECT resides. The accessibility of member methods follows the same rules, such as:

func (r *Rect) area() float64 {     

This Rect way, the area() method can only be used within the same package as the type.
One thing to note is that the accessibility of symbols in the Go language is package-level rather than type-level. In the example above, although area() it is an Rect internal method, other types in the same package can also access it. This kind of accessibility control is very rough, very special, but very practical. If the accessibility of the Go language symbol is type-level, you need to add a keyword like friend to indicate that two classes are friends and can access each other's private members.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.