Declaring a new instance of T on the heap with new

Consider the following example (Golang playground):

  1. func NewT[T any]() *T {
  2. var t *T
  3. return t
  4. }
  5. func main() {
  6. fmt.Println(NewT[int]())
  7. }

The above program will print <nil> because NewT[T] *T returns a *T with a nil value since there was no instance of a T allocated. Now consider (Golang playground):

  1. func NewT[T any]() *T {
  2. return new(T)
  3. }
  4. func main() {
  5. fmt.Println(NewT[int]())
  6. }

Now the output will be a memory address that references a new instance of an int value. This means we can also clean up our example from the previous page so there is no longer a need to assign sum to the default value of T since new(T) allocates that for us (Golang playground):

  1. func Sum[T Numeric](args ...T) T {
  2. sum := new(T)
  3. for i := 0; i < len(args); i++ {
  4. *sum += args[i]
  5. }
  6. return *sum
  7. }

And just like with var t, a new T allocated with new can still be inlined and optimized to the stack instead of escaping to the heap:

  1. $ docker run -it --rm go-generics-the-hard-way \
  2. go run -gcflags "-m" ./04-getting-going/02-new-t/stack
  3. # go-generics-the-hard-way/04-getting-going/02-new-t/stack
  4. 04-getting-going/02-new-t/stack/main.go:32:6: can inline Sum[go.shape.int_0]
  5. 04-getting-going/02-new-t/stack/main.go:41:17: inlining call to Sum[go.shape.int_0]
  6. 04-getting-going/02-new-t/stack/main.go:41:13: inlining call to fmt.Println
  7. 04-getting-going/02-new-t/stack/main.go:41:13: ... argument does not escape
  8. 04-getting-going/02-new-t/stack/main.go:41:17: ~R0 escapes to heap
  9. 04-getting-going/02-new-t/stack/main.go:41:17: ... argument does not escape
  10. 04-getting-going/02-new-t/stack/main.go:41:17: new(go.shape.int_0) does not escape
  11. 04-getting-going/02-new-t/stack/main.go:33:12: new(go.shape.int_0) does not escape
  12. 6

Still, regardless of how a new T is allocated, there is a ticking timebomb when discussing *T that will be covered at the end of this section.


Next: Structs