Thursday, April 5, 2012

Difference between new() and make()

There are two basic types in Go :

Value types - They contain the actual data. They are char, bool, int, float, string. These types are stored on stack.

Reference types - They contain the memory address which points to actual data. Examples are slice, maps and channels. These types are stored on heap.

The new() function is useful only for value types. It returns the address where the type T is stored in the heap.

Since the reference types are already addresses we use make() function which returns the value of type T.

In short :
- new() is used for value types and make() is used for reference types.
- new() returns a address and make() returns a value.

If we do a new() on reference types it returns a address, which itself points to a address where the type T is stored.

Consider the following slice example :
s1 := new([]int)
This returns the address that points to a slice. Since slice is a reference type, the slice itself is a address which points to where the actual data is stored. Thats why we use
s1 := make([]int, 10)
This returns the actual slice.

No comments:

Post a Comment