Go language Learning-structure

Source: Internet
Author: User

Structural body

A struct in the go language, a composite type with a set of attributes called fields. Structs are also value types and can be created using new.

Defined:

type name struct {    field1 type1    field2 type2    ...}

We can see that each field consists of a name and a type, but in fact, if we don't need to use a field, we can use "_" instead of its name.

And the struct field can be any type, function, interface, or even struct itself can be

Working with structural bodies

Define a person structure body

type Person struct {    name string    age  int}

Use

// 字面量形式初始化var p1 = Person{    name: "Tom",    age: 18,}var p2 = Person{"Cat", 20}fmt.Println(p1)          //{Tom 18}                                                                                     fmt.Println(p1.name)     // Tomfmt.Println(p2)          // {Cat 20}p1.age = 20      // 设置p的age字段的值fmt.Println(p1)     // {Tom 20}还可以使用new函数来给一个结构体分配内存,并返回指向已分配内存的指针var p3 *Person   // 声明一个Person类型的指针p3 = new(Person)   // 分配内存// 上面两句相当于p3 := new(Person)p3.name = "Cat"p3.age = 10fmt.Println(p3)       // &{Cat 10}fmt.Println(p3.name)  

We can use the struct pointer directly through the "." To access the fields of the struct, like directly using a struct instance, go will automatically convert

There is also a syntax called mixed literal to declare, as follows, this is actually a shorthand method, the underlying or call the new method

var p4 = &Person{"Dog", 10}  // 同样返回的是Person类型的指针fmt.Println(p4)             // &{Dog 10}fmt.Println(p4.name)        // Dog
Anonymous fields

The go language structure also supports anonymous fields, that is, a field that has only a type but no field name (not even "_"), which can also be of any type, when the type name is the name of the field, that is, we can access the anonymous field directly using the type name by.

In addition, if the anonymous field is another struct, this is called an inline struct, which simulates behavior similar to inheritance.

type Person struct {    name string    age  int}type Student struct {    Person    int}// 定义一个Student类型的变量var s = Student{Person{"gdb", 10}, 10}// 可以使用如下的方法访问内部结构体中的字段fmt.Println(s.Person.name)// 也可以这样访问,go将自动使用Person的name属性,不过如果在Student中也定义了name字段,这里就不能使用了fmt.Println(s.name)// 访问int类型的匿名字段,此时类型就是字段的名字fmt.Println(s.int)

Note: If two fields have the same name, the external name will overwrite the inner one, and if the same name field is present at the same level, it will be an error, need attention, and cannot be nested at the same time. Type and its pointer type because they have the same name.

Label

A field in a struct can have a label in addition to its name and type. It is a string attached to a field, which can be a document or other important token. Say the reflection later.

Method

Previously learned object-oriented languages, such as Java, Python, have the concept of a class, each class can have its own member variables, member methods, which are defined in the class

The structure of the go language is similar to the object-oriented language class, and the structure of the field is equivalent to the member variables in the class, the struct can also have methods, but not directly defined in the structure, the go language has a receiver concept, we can function in a receiver, this function is called a method

The receiver is some type of variable, not just a struct, almost any type can be a struct, such as: Int,bool, string or array alias type, or even function type, but not interface type

Example of defining a method:

type Person struct {    name string    age int}// 使用Person类型的实例做接收者,这就是一个Person类型方法,方法名前面括号中的就是接收者func (this Person) getName() string {    return this.name}// Peron类型的指针对象也可以作为接收者func (this *Person) setName(name string) {    this.name = name}tom := Person{"Tom", 20}fmt.Println(tom)  // {Tom 20}fmt.Println(tom.getName())  // Tomtom.changeName("Bob")fmt.Println(tom)  // {Bob 20}

Here's one thing to note: The type and the method that binds it must be in the same package (not necessarily in the same file)

Here the use of the type directly as the receiver and type of the pointer as the recipient of the difference, is equivalent to the normal function, the value type of the parameter and the reference type parameter, that is, the operation of the instance of the type in the method does not affect the value of the external instance, and uses the instance of the type pointer as the reference parameter. Internal modification of a method can affect an external instance

Anonymous fields

We can also use the anonymous field inside the struct as the receiver of the method, at which point the struct can still call this method, where the compiler is responsible for finding

type Person struct {    name string    age int}type Student struct {    Person    score int}func (p *Person) show() {    fmt.Println("My name is " + p.name + ", I‘m " + strconv.Itoa(p.age) + " years old")}tom := Person{"Tom", 20}// 调用匿名字段作为接收器的方法tom.show()   // My name is Tom, I‘m 20 years old

On this basis, we can also implement a method with the same name as an anonymous field on the struct, just like in object-oriented overrides, where the compiler first looks for the struct instance as the receiver's method.

Method set

Depending on the definition of the struct and the method, the set of methods is different, understanding them and helping to understand the interface

type T struct {    name string    age int}type G struct {    T    action string}type S struct {    *T    sel string}
    • The set of methods of type T contains all methods for which the recipient is T
    • the set of methods of type T contains all methods for which the recipient is T (because go will automatically dereference) and all methods that the recipient is T
    • Type G contains the anonymous field T, then the method set of G, containing only the method set of type T
    • Type S contains the anonymous field *t, the method set of S, which contains the T and *t types of the method set

Go language Learning-structure

Related Article

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.