Golang built-in functions the difference between the initialization of new () and struct{}
Happinessaflower 2015-06-17 20:03:41 13,036 reads • Estimated reading time 1 minutes • Start browsing about 1 minutes ago
This is an article created in 2015-06-17 20:03:41, where the information may have evolved or changed.
New ()
This is a built-in function for allocating memory, the first parameter of which is a type, not a value, and its return value is a pointer to a 0 value of the newly assigned T type.
The code in Golang is defined as follows:
Funcnew (ttype) *type
strut{}
When initializing strut directly using struct{}, the value returned is a struct type, not a pointer.
The comparison code is as follows:
typestudentstruct{Idintnamestring}funcmain () {vars_1 *student =new (Student) s_1.id = 100s_1.name = "Cat" Vars_2 Studen t = student{id:1,name: "Tom"} FMT. Println (S_1,s_2)}
Output Result:
&{100 Cat} {1 Tom}
From the declaration of the above Code and the result of printing, we can see that the type of s_1 is a pointer, s_2 is a student type