Home  >  Article  >  Backend Development  >  Detailed explanation of Go language structure and initialization graphic and text

Detailed explanation of Go language structure and initialization graphic and text

尚
forward
2020-01-09 17:54:343047browse

Detailed explanation of Go language structure and initialization graphic and text

Go supports user-defined types through type aliases (alias types) and structures.

Structure is a composite type. When you need to define a type, which consists of a series of attributes, each attribute has its own type and value, you should use a structure, which gathers data together.

Structures are also value types, so you can use the new function to create

The data that make up the structure type become fields. Each field has a type and a name; within a structure, field names must be unique.

1. Structure definition

The general way of defining a structure is as follows:

type identifier struct {   
   field type1
    field type2}

type T struct {a, b int} is also a legal syntax. It is more suitable for simple structures.

The fields in the structure have names, such as field1, field2, etc. If the fields are never used in the code, Then you can name it _.

The naming of structure types and fields follows visibility rules, so there may be some fields of a structure type that are exported, while others are not.

The fields of the structure can be of any type, even the structure itself, or it can be a function or interface. You can declare a variable of a structure type and then assign values ​​to its fields like this:

var s T
s.a = 5
s.b = 8

An array can also be regarded as a structure type, but it uses subscripts instead of named fields

Second, initialization

#Method 1: Declare the structure through var

In Go language When a variable is declared, the system will automatically initialize its default value. For example, int is initialized to 0 and the pointer is nil.
The var declaration will also allocate memory for structure type data, so we can directly assign values ​​to its fields after declaring var s T like in the previous code.

Method 2: Use new

Use the new function to allocate memory to a new structure variable. It returns a pointer to the allocated memory: var t *T = new(T).

type struct1 struct {
    i1 int
    f1 float32
    str string}func main() {
    ms := new(struct1)
    ms.i1 = 10
    ms.f1 = 15.5
    ms.str= "Chris"

    fmt.Printf("The int is: %d\n", ms.i1)
    fmt.Printf("The float is: %f\n", ms.f1)
    fmt.Printf("The string is: %s\n", ms.str)
    fmt.Println(ms)
}

Same as object-oriented languages, you can use the dot operator to assign values ​​to fields: structname.fieldname = value.

Similarly, you can use the dot operator to get the value of the structure field: structname.fieldname.

Method 3: Use literals

type Person struct {
    name string
    age int
    address string
}

func main() {
    var p1 Person
    p1 = Person{"lisi", 30, "shanghai"}   //方式A
    p2 := Person{address:"beijing", age:25, name:"wangwu"} //方式B
    p3 := Person{address:"NewYork"} //方式C
}

In (Method A), the values ​​must be given in the order in which the fields are defined in the structure. (Method B) adds the field name and colon in front of the value. In this method, the order of the values ​​does not have to be consistent, and some fields can be ignored, just like (Method C).

In addition to the above three methods, there is a shorter and more common way to initialize the structure entity, as follows:

ms := &Person{"name", 20, "bj"}
ms2 := &Person{name:"zhangsan"}

&Person{a, b, c} is an abbreviation, The bottom layer will still call new(), where the order of the values ​​must be written in the order of the fields. It can also be written by adding the field name and colon in front of the value (see methods B and C above).

The expressions new(Type) and &Type{} are equivalent.

3. The difference between several initialization methods

So far, we have learned about three ways to initialize a structure:

//第一种,在Go语言中,可以直接以 var 的方式声明结构体即可完成实例化
var t T
t.a = 1
t.b = 2

//第二种,使用 new() 实例化
t := new(T)

//第三种,使用字面量初始化
t := T{a, b}
t := &T{} //等效于 new(T)

Using var t T will allocate memory for t and zero-value the memory, but the type of t at this time is T

When using the new keyword t := new(T) , the variable t is a pointer to T

From the memory layout, we can see the difference between these three initialization methods:

Use var statement:

Detailed explanation of Go language structure and initialization graphic and text

Use new to initialize:

Detailed explanation of Go language structure and initialization graphic and text

Use structure literal to initialize:

Detailed explanation of Go language structure and initialization graphic and text

Let’s look at a specific example:

package main
import "fmt"

type Person struct {
 name string
 age int
}

func main() {
 var p1 Person
 p1.name = "zhangsan"
 p1.age = 18
 fmt.Printf("This is %s, %d years old\n", p1.name, p1.age)

 p2 := new(Person)
 p2.name = "lisi"
 p2.age = 20
 (*p2).age = 23 //这种写法也是合法的
 fmt.Printf("This is %s, %d years old\n", p2.name, p2.age)

 p3 := Person{"wangwu", 25}
 fmt.Printf("This is %s, %d years old\n", p3.name, p3.age)
}

Output:

This is zhangsan, 18 years old
This is lisi, 23 years old
This is wangwu, 25 years old

In the second case of the above example, although p2 is a pointer type, we can still like p2.age = 23 For assignment, there is no need to use the -> operator like in C, Go will automatically convert it.

Note that you can also use the * operator to get the content pointed to by the pointer first, and then assign it: (*p2).age = 23.

Memory layout of structure

Go 语言中,结构体和它所包含的数据在内存中是以连续块的形式存在的,即使结构体中嵌套有其他的结构体,这在性能上带来了很大的优势。不像 Java 中的引用类型,一个对象和它里面包含的对象可能会在不同的内存空间中,这点和 Go 语言中的指针很像。

下面的例子清晰地说明了这些情况:

type Rect1 struct {Min, Max Point }
type Rect2 struct {Min, Max *Point }

Detailed explanation of Go language structure and initialization graphic and text

更多go语言知识请关注PHP中文网go语言教程栏目。

The above is the detailed content of Detailed explanation of Go language structure and initialization graphic and text. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete