Detailed explanation of Struct structure in go

content

First, the structure definition

1. Definition of structure

2. Visibility of structure fields

3. Anonymous fields of structures

Second, the structure instantiation

1. Basic instantiation

2, needle type instantiation

3. Take address instantiation

Three, structure initialization

1. Two initialization methods

2. Use "key-value pairs", two initializations of value lists

Fourth, use the structure to implement the constructor

Fifth, the "inheritance" of the structure


First, the structure definition

        The basic data types in the Go language can represent the basic properties of some things, but when we want to express all or part of the properties of a thing, it is obviously not enough to use a single basic data type at this time. Go language provides a A custom data type that can encapsulate multiple basic data types. This data type is called a structure, and the English name is struct. That is, we can define our own type through struct.

Object orientation is implemented in Go language through struct.

1. Definition of structure

type 类型名 struct {
    字段名 字段类型
    字段名 字段类型
    …
}

1. Type name: The name that identifies the custom structure, which cannot be repeated in the same package.

2. Field name: Indicates the structure field name. Field names in a structure must be unique.

3. Field type: Indicates the specific type of the structure field.

For example, let's define a Person structure with the following code:

type person struct {
    name string
    city string
    age  int8
}

Fields of the same type can also be written on one line,

type person1 struct {
    name, city string
    age        int8
}

In this way, we have a custom type of person, which has three fields: name, city, and age, which represent name, city and age respectively. In this way, we can use this person structure to easily represent and store person information in the program.

2. Visibility of structure fields

Fields in a struct that start with uppercase indicate public access, and lowercase indicate private (accessible only in the package that defines the current struct).

3. Anonymous fields of structures

A structure allows its member fields to be declared with only the type and no field name. This kind of field without a name is called an anonymous field.

//Person 结构体Person类型
type Person struct {
    string
    int
}

func main() {
    p1 := Person{
        "pprof.cn",
        18,
    }
    fmt.Printf("%#v\n", p1)        //main.Person{string:"pprof.cn", int:18}
    fmt.Println(p1.string, p1.int) //pprof.cn 18
    
}

        Anonymous fields use the type name as the field name by default. Since the structure requires that the field name must be unique, there can only be one anonymous field of the same type in a structure.

Second, the structure instantiation

notes: If declared first, then instantiated. struct can only be used after instantiation

The definition of a structure is just a description of the memory layout, and only when the structure is instantiated, the memory is actually allocated. Therefore, the fields of the struct must be defined and instantiated before the struct's fields can be used.

Instantiation is to create a memory area consistent with the format according to the format defined by the structure. The memory between the structure instance and the instance is completely independent.

1. Basic instantiation

The structure itself is a type, which can be instantiated by declaring the structure in the form of var, just like types such as integers and strings.

var ins T
type person struct {
    name string
    city string
    age  int8
}

func main() {
    var p1 person
    p1.name = "pprof.cn"
    p1.city = "北京"
    p1.age = 18
    fmt.Printf("p1=%v\n", p1)  //p1={pprof.cn 北京 18}
    fmt.Printf("p1=%#v\n", p1) //p1=main.person{name:"pprof.cn", city:"北京", age:18}
}

2, needle type instantiation

In the Go language, you can also use the new keyword to instantiate types (including structures, integers, floating-point numbers, strings, etc.), and the structure will form a pointer-type structure after instantiation.

The format for using new is as follows:

ins := new(T)

The Go language allows us to access the members of a structure pointer just like a normal structure .

type Player struct{
    Name string
    HealthPoint int
    MagicPoint int
}

//指针类型
tank := new(Player)

tank.Name = "Canon"
tank.HealthPoint = 300

The structure instance instantiated by new is the same as the basic instantiation in terms of member assignment.

3. Take address instantiation

          In the Go language, when performing & taking the address operation on a structure, it is regarded as a new instantiation operation for the type. The address format is as follows:

ins := &T{}

The following uses a structure to define a command-line command (Command), which contains names, variable associations, and comments. Instantiate the pointer address of Command and complete the assignment process. The code is as follows:

type Command struct {
    Name    string    // 指令名称
    Var     *int      // 指令绑定的变量
    Comment string    // 指令的注释
}

var version int = 1

cmd := &Command{}

cmd.Name = "version"
cmd.Var = &version
cmd.Comment = "show version"

Important: Address instantiation is the most extensive way to instantiate a structure.

func newCommand(name string, varref *int, comment string) *Command {
    
    return &Command{
        Name:    name,
        Var:     varref,
        Comment: comment,
    }
}

cmd = newCommand(
    "version",
    &version,
    "show version",
)

Three, structure initialization

When a structure is instantiated, member variables can be initialized directly. Equivalent to direct assignment when instantiating

1. Two initialization methods

There are also two ways to initialize, direct initialization and address initialization.

//1、直接实例化
p5 := person{
    name: "pprof.cn",
    city: "北京",
    age:  18, //最后一个逗号必须存在,否则会报错
}

//2、取地址实例化
p6 := &person{
    name: "pprof.cn",
    city: "北京",
    age:  18, //最后一个逗号必须存在,否则会报错
}

//备注:没有指针类型的初始化

2. Use "key-value pairs", two initializations of value lists

One is in the form of a field "key-value pair" and a list of multiple values. The initialization in the form of key-value pairs is suitable for selectively filling structures with many fields;

Lists of multiple values ​​are suitable for structs with fewer fields to fill. (To put it bluntly, don't write the key, just write the value directly)

(1) Initialize the structure with a "key-value pair"

Filling of key-value pairs is optional, and fields that do not need to be initialized may not be filled in the initialization list.

The default value of the field after the structure is instantiated is the default value of the field type, for example: the value is 0, the string is an empty string, the boolean is false, the pointer is nil, etc.

The format of key-value pair initialization is as follows:

ins := 结构体类型名{
    字段1: 字段1的值,
    字段2: 字段2的值,
    …
}

//示例一:
p5 := person{
    name: "pprof.cn",
    city: "北京",
    age:  18, //最后一个逗号必须存在,否则会报错
}

fmt.Printf("p5=%#v\n", p5) //p5=main.person{name:"pprof.cn", city:"北京", age:18}

//示例二:也可以对结构体指针进行键值对初始化
p6 := &person{
    name: "pprof.cn",
    city: "北京",
    age:  18, //最后一个逗号必须存在,否则会报错
}
fmt.Printf("p6=%#v\n", p6) //p6=&main.person{name:"pprof.cn", city:"北京", age:18}

(2) Use list initialization of values

When initializing the structure, it can be abbreviated, that is, the key is not written when initializing, but the value is directly written:

p8 := &person{
    "pprof.cn",
    "北京",
    18,
}
fmt.Printf("p8=%#v\n", p8) //p8=&main.person{name:"pprof.cn", city:"北京", age:18}

When initializing with this format, you need to pay attention:

  • All fields of the structure must be initialized.
  • The order in which the initial values ​​are populated must match the order in which the fields are declared in the structure.
  • This method cannot be mixed with the key-value initialization method. (That is, you can't write the key at once, and don't write the key at once)

Fourth, use the structure to implement the constructor

A type or struct in go has no constructor function. The initialization process of a structure can be implemented using function encapsulation.

Because struct is a value type, if the structure is complex, the value copy performance overhead will be relatively large, so the constructor returns a structure pointer type.

func newPerson(name, city string, age int8) *person {
    return &person{
        name: name,
        city: city,
        age:  age,
    }
}

call the constructor

p9 := newPerson("pprof.cn", "测试", 90)
fmt.Printf("%#v\n", p9)

Fifth, the "inheritance" of the structure

The use of structs in Go can also implement object-oriented inheritance in other programming languages.

Description: This only simulates "inheritance"

//Animal 动物
type Animal struct {
    name string
}

func (a *Animal) move() {
    fmt.Printf("%s会动!\n", a.name)
}

//Dog 狗
type Dog struct {
    Feet    int8
    *Animal //通过嵌套匿名结构体实现继承
}

func (d *Dog) wang() {
    fmt.Printf("%s会汪汪汪~\n", d.name)
}

func main() {
    d1 := &Dog{
        Feet: 4,
        Animal: &Animal{ //注意嵌套的是结构体指针
            name: "乐乐",
        },
    }
    d1.wang() //乐乐会汪汪汪~
    d1.move() //乐乐会动!
}

 

Guess you like

Origin blog.csdn.net/demored/article/details/124197369