No F*cking Idea

Common answer to everything

Golang New & Make

| Comments

When i first started playing and learning Google GO one if the first things i noticed was new and make. At first glance they seemed to be doing same thing. There is a difference and it actually is quite easy to explain.

Documentation

If we will go to the golang doc page under http://golang.org/pkg/builtin we can see every builtin function in go. Also new and make. From new we can read.

“The new built-in function allocates memory. The first argument is a type, not a value, and the value returned is a pointer to a newly allocated zero value of that type.”

similar on make.

“The make built-in function allocates and initializes an object of type slice, map, or chan (only). Like new, the first argument is a type, not a value. Unlike new, make’s return type is the same as the type of its argument, not a pointer to it.”

So we can see that new return pointer to a type and make returns an allocated object of that type. Now this is a difference.

So how can we implement a simplified new ?

1
2
3
4
5
func newInt() *int {
  var i int
  return &i
}
someVar := newInt()

this is just like we would do someVar := new(int).

In case of make we can only use it for map, slice and chan.

“Slice: The size specifies the length. The capacity of the slice is equal to its length. A second integer argument may be provided to specify a different capacity; it must be no smaller than the length, so make([]int, 0, 10) allocates a slice of length 0 and capacity 10. Map: An initial allocation is made according to the size but the resulting map has length 0. The size may be omitted, in which case a small starting size is allocated. Channel: The channel’s buffer is initialized with the specified buffer capacity. If zero, or the size is omitted, the channel is unbuffered.”

make creates and allocates all the memory. We can specify size of the element we want in the second parameter but this only works for slice and chan. Map is a special type that doesn’t need size.

And make is the only way to create this objects.

Summary

new is a way of getting pointers to new types while make is for creating channels, maps and slices only.

Comments