0

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?

dastan
  • 1,006
  • 1
  • 16
  • 36
  • 1
    See also http://stackoverflow.com/a/25358332/6309 – VonC Sep 09 '14 at 10:35
  • 1
    possible duplicate of [What is the difference between new and make?](http://stackoverflow.com/questions/25358130/what-is-the-difference-between-new-and-make) – OneOfOne Sep 09 '14 at 12:49

3 Answers3

8

I've written about this on my blog.

http://dave.cheney.net/2014/08/17/go-has-both-make-and-new-functions-what-gives

Dave Cheney
  • 5,575
  • 2
  • 18
  • 24
3

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.

Community
  • 1
  • 1
Emil Davtyan
  • 13,808
  • 5
  • 44
  • 66
1

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.
newacct
  • 119,665
  • 29
  • 163
  • 224