Initialization process structured body golang (new method)

A custom structure

 

type Rect struct {

    x, y float64

    width, height float64

}

Initialization method:

 

 

rect1 := new(Rect)

rect2 := &Rect{}

rect3 := &Rect{0, 0, 100, 200}

rect4 := &Rect{width:100, height:200}

Note that all of these variables is a pointer (a pointer variable) Rect structure, since the new () function and & operator. If use

 

a := Rect{}

This indicates a type Rect {}. The two are not the same. Reference Code:

 

func main() {

rect1 := &Rect{0, 0, 100, 200}

rect1.x = 10

 

a := Rect{}

a.x = 15

 

fmt.Printf("%v\n%T\n", a, a)

fmt.Printf("%v\n%T\n", rect1, rect1)

}

Operating results as follows:

 

{15 0 0 0}

 main.Rect

 &{10 0 100 200}

 *main.Rect

From the results we can clearly see the difference.

 

However, in Go, a zero value is initialized for the type of variables are initialized not performed, for example, a value of zero bool type false, int type value of zero 0, string type zero is the empty string. Go language is not in the concept constructor to create an object is usually referred to the creation of a global function to complete, in order to NewXXX command, which means "constructor":

 

func NewRect(x ,y ,width, height float64) {

    return &Rect{x, y, width, height}

}

This is all very natural. Developers do not need to analyze in the end how much things happened behind after using the new. In the Go language, all the things you want to happen can be seen directly. Attachment:

 

Allocate memory with the new built-in functions with the same name as the new essence function as functions in other languages: new (T) is assigned a value of zero padding of the type of memory T and returns its address, a value of type * T. Go terminology that it returns a pointer to the newly allocated zero value of type T. Remember that this is very important. This means that users can create an instance of a data structure and can work directly with the new. The bytes.Buffer document as "zero value Buffer is an empty buffer ready." Similar, sync.Mutex no explicit constructor or Init method. Instead, a value of zero is defined sync.Mutex non mutex lock. Zero values ​​are very useful. For example, the definition of this type, "define your own type of" content of 56. ===================

 

Always remember to make apply only to map, slice and channel, and not return pointer. Pointer should be obtained with specific new.

https://studygolang.com/articles/4974

Published 455 original articles · won praise 77 · Views 1.31 million +

Guess you like

Origin blog.csdn.net/az44yao/article/details/103542735