What is the difference between Go's make function and new function?
In Go, make and new are two built-in functions that are used for allocating memory. However, they are used for different purposes.
The **new**
function is used to allocate memory for a new value of a specified type and returns a pointer to the newly allocated memory. The new function initializes the memory to the zero value of the type. For example:
var i *int
i = new(int)
In this example, **i**
is a pointer to an integer that has been allocated with the **new**
function. **i**
will be initialized to the zero value of the integer type (which is **0**
).
The **make**
function, on the other hand, is used to allocate and initialize slices, maps, and channels. It returns an initialized (not zeroed) value of the specified type. For example:
s := make([]int, 5)
In this example, **s**
is a slice of integers that has been allocated and initialized with the **make**
function. The slice has a length of 5 and all its elements are initialized to the zero value of the integer type (**0**
).
In summary, **new**
is used to allocate memory for a single value of a specified type, while **make**
is used to allocate and initialize memory for slices, maps, and channels.