10

Say I have a struct:

type foo struct {
}

Are there any difference between

f := &foo{}

and

f := new(foo)

in terms of the machine code it gets compiled into, or it's just merely a syntax difference?

A more specific question:

As for struct literal (&foo{}), the memory can be allocated in stack or heap, depends on the escape analysis.

However for new(foo), I am not quite sure:

calloc() in c is similar to new() in golang from my understanding. But calloc() always allocate on heap. I am wondering if new() always allocate in heap?

The golang spec (https://golang.org/ref/spec#Allocation) only mentioned:

The built-in function new takes a type T, allocates storage for a variable of that type at run time, and returns a value of type *T pointing to it. The variable is initialized as described in the section on initial values.

It does not say where new() will allocate the memory. So does new() always allocate on heap, or it can also be allocated in stack as well --- Exactly same as struct literal in memory allocation?

Helin Wang
  • 4,002
  • 1
  • 30
  • 34

0 Answers0