What is the difference between new (Struct) and & Struct {} in Go?

They seem the same:

package main import "fmt" type S struct { i int } func main() { var s1 *S = new(S) fmt.Println(s1) var s2 *S = &S{} fmt.Println(s2) // Prints the same thing. } 

Update:

Hm. I just realized that there is no obvious way to initialize Si using a new one. Is there any way to do this? new(S{i:1}) doesn't seem to work: /

+7
go
source share
2 answers

From the documentation :

As a limiting case, if a composite literal contains no fields at all, it creates a null value for the type. The expressions new (File) and & File {} are equivalent.

+7
source share

They not only give the same resulting value, but also highlight something in both directions and look at their values ​​...

 // Adapted from http://tour.golang.org/#30 package main import "fmt" type Vertex struct { X, Y int } func main() { v := &Vertex{} v2 := new(Vertex) fmt.Printf("%p %p", v, v2) } 

... we will see that they are actually distributed in consecutive memory slots. Typical Output: 0x10328100 0x10328108 . I'm not sure if this is an implementation detail or part of a specification, but it shows that they are both allocated from the same pool.

Play here with the code.

As for initialization with new, according to the language specification : The built-in function new takes a type T and returns a value of type *T. The memory [pointed to] is initialized as described in the section on initial values. The built-in function new takes a type T and returns a value of type *T. The memory [pointed to] is initialized as described in the section on initial values. Since functions in go cannot be overloaded, and it isn’t a variational function, there is no way to pass any initialization data. Instead, go will initialize it with any version 0 makes sense for the type and any member fields, if necessary.

0
source share

All Articles