Learn Go: 12. Custom types and structures - Definitions

Keywords: Go struct

Address of official account

Learn what

  1. How to customize a type?

  2. How to define a structure?

  3. How to initialize a structure?

  4. How to nest structures?

  5. How to define anonymous structures?

  6. How to alias a type?

  7. How to define structure labels?

concept

What is a custom type? When the built-in types in Go language, such as int, string, etc., cannot meet the requirements, you can customize a type.

Create custom type

1. Based on built-in type

type typeName baseType
  • typeName is the defined type name

  • baseType depends on types. All data types in Go language are OK. The structure struct to be discussed later

For example, the following three custom types all depend on built-in types.

type str string

type num int

type m map[string]string

In the above example, although str type depends on string type, it is a strongly typed language in Go language, that is, the two types cannot be compared directly.

If str and string types are compared, type conversion is required, as is the case for other custom types.

var s1 str = "new string"

// str to string type

s2 := string(s1)

2. Structure

A structure is a composite type in a user-defined type, which can contain multiple different data types.

Defines a structure of type People, which contains two type fields.

type People struct {

    // field

    *Name string*

    Age  int

}

When the field types are the same, the same can be declared only once.

type StructName struct {

    Name string

    Age, Weight int

}

If you want to write the fields in the structure in one line, you need to use the "English semicolon" to separate them. In order to make the structure of the code clear, this is generally not used.

type OneLine struct{Name string; Age, Weight int}

You can also define no fields in the structure, that is, an empty structure.

type EmptyStruct struct {}

Note:

  • Use the struct keyword to define.

  • The struct keyword must be followed by "{", that is, on the same line.

Initialize structure

After the structure is defined, the initialization value is required.

1. With field name

p1 := People{

    Name: "Old seedling",

    Age:  18,

}

When assigning a value to a field, you can set only a part or none. If it is not set, it will follow the default value.

p := People{

    Age:  18,

}

exmaple := People{}

Name is an empty string by default, and Age is 0 by default.

2. Without field name

When setting the field value, you can not take the field name. At this time, you must assign values according to the structure field order.

p2 := People{

    "Old seedling",

    18,

}
  • Partial omission is not allowed during assignment.

  • Names with and without fields cannot be mixed.

Accessing structure fields

Use point to access and set field values

p := People{"Old seedling", 18}

// Access field

fmt.Println(p.Name)

// Set field

p.Name = "Chic brother"

Structure nesting

In one structure, another structure can be nested. This feature is somewhat similar to inheritance in object-oriented.

type People struct {

    Name string

    Age  int

}

type Student struct {

    People

    Collect string

}

In the Student structure, the People structure is nested. When nesting, you do not need to set the field name. At this time, the default field name is the nested type name.

1. Initialization

There are two ways to initialize the Student structure, one with field name and the other without field name.

// First: with field name

s1 := Student{

    People: People{

        Name: "Old seedling",

        Age:  18,

    },

    Collect: "Don't tell",

}

// Second: without field name

s2 := Student{

    People{

        Name: "Old seedling",

        Age:  18,

    },

    "Don't tell",

}

2. Access nested structures

In the above example, the People structure is embedded in the Student structure and the field name is not defined. In this case, there are two ways to obtain the fields in the People structure.

The first method: access without field name, because the fields in the People and Student structures will become the same level, and the method carried by the structure (explained in the next chapter) is the same.

s2.Name

The second method is to access the field name. The field name is not written during embedding. The default field name is the embedded type name.

s2.People.Name

3. Same field name

When the embedded structure has the same field Name as the parent structure, the compiler can pass. For example, the Name field in the RepeatStudent structure has the same Name as the Name field in the People structure. In this case, the Name field in the People structure must be accessed with the structure Name.

type RepeatStudent struct {

    People

    Collect string

    Name string

}

r := RepeatStudent{

    People: People{Name: "Old seedling"},

    Name:   "Chic brother",

}

fmt.Println(r.Name, r.People.Name)

// output

Handsome brother and Miao

Anonymous structure

Anonymous structure means that there is no structure name. Like anonymous functions, there is no name.

ano := struct {

   Name string

}{

   Name: "anonymous",

}

The code defines an anonymous structure and contains a field, which is initialized after definition.

Anonymous structures can also be used when nesting structures.

type AnoStudent struct {

    People struct {

        Name string

        Age  int

    }

    Collect string

}

Structure label

When defining a structure, you can write labels on the fields and customize the of the structure through labels.

For example, using the standard package "encoding/json" to convert json string, you can declare to convert the structure field to the corresponding name through the tag.

type Tag struct {

    Name string `json:"name"`

}

t := Tag{"tag"}

b, _ := json.Marshal(t)

fmt.Println(string(b))

// output

{"name":"tag"}

Wrap the label with back quotation marks. The rules of the label depend on how the processing method or function is defined. How to obtain the label is not explained here.

Type alias

This is different from the user-defined type. The type alias is completely equivalent to the original type. There is no need for type conversion, but the name is different.

type byte = uint8

In built-in types, byte type is the alias of uint8 type.

summary

This chapter explains how to customize a type and explains the structure in detail. You must master it, but you haven't finished yet. The next chapter explains how to carry a user-defined type.

After you have learned the object-oriented language and know the concept of class, let me compare the similarities between class and structure.

  • Class attribute - struct field

  • Class method - struct method (Part 2)

  • Class inheritance - structure nesting

This is also when transforming the object-oriented language, the structure of Go language is replaced as a class.

Posted by Leonardo Dantas on Mon, 11 Oct 2021 22:40:45 -0700