This is a creation in Article, where the information may have evolved or changed.
Transferred from: http://my.oschina.net/ifraincoat/blog/517139
Customizing a struct
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 these variables are all pointers to the RECT structure (pointer variables) because the new () function and the & operator are used. And if you use methods
A: = rect{}
Indicates that this is a rect{} type. 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)
}
The result of the operation is:
{15 0 0 0}
Main. Rect
&{10 0 100 200}
*main. Rect
The difference between the two can be clearly seen from the results.
In the go language, variables that are not initialized are initialized to 0 values of that type, such as the 0 value of the bool type is false, the 0 value of the int type is 0, and the string type 0 value is an empty string. In the go language there is no concept of constructors, and the creation of objects is usually done by a global creation function, with the NEWXXX command to represent "constructors":
Func newrect (x, y, width, height float64) {
Return &rect{x, y, width, height}
}
It's all very natural. Developers do not need to analyze how many things have happened behind the use of new. In the go language, everything that's going to happen is directly visible. Report:
Allocating an in-memory built-in function with new new is essentially the same as the function of the same name in other languages: new (t) allocates a 0 value to fill the memory space of type T, and returns its address, a value of type *t. In the terms of Go, it returns a pointer to the 0 value of the newly assigned type T. It is important to remember this. This means that the user can create an instance of the data structure with new and can work directly. such as bytes. The "0 value of buffer" as described in the documentation for buffer is a prepared null buffer. "Similar, sync. The Mutex also has no explicit constructor or Init method. Instead, sync. The 0 value of a mutex is defined as a non-locked mutex. A value of 0 is very useful. For example, for a type definition, 56 pages of the "Define your own type" content. ===================
Make sure that make is only available for Map,slice and channel, and is not a pointer returned. A specific pointer should be obtained with new.