make和new实际做什么?

In Go, if I want to create an Object of T, I can try these ways:

t := T{} // t is the actual object created in the current stack
p := &T{} // p is a pointer points to the actual object which is created in the current stack
p := make(T) // p is a pointer points to the actual object which is created in the heap
p := new(T) // p is a pointer points to the actual object which is created in the heap

I'm wondering whether my comments are correct or not?

t := T{} // t is the actual object created in the current stack

p := &T{} // p is a pointer points to the actual object which is created in the current stack

p := make(T) // p is a pointer points to the actual object which is created in the heap

p := new(T) // p is a pointer points to the actual object which is created in the heap

I'm wondering whether my comments are correct or not?

Not quite, whether an object is allocated on the stack or the heap depends on escape analysis not the particular notation used to instantiate the object and actually Dave wrote something about that also.

Looking at the type of the result is instructive.

  • make(T, ...) returns type T. make can only be used for a few built-in types (slice, map, channel). It is basically a "constructor" for those types.
  • new(T) returns type *T. It works for all types and does the same thing for all types -- it returns a pointer to a new instance of type T with zero value.