In Go, make
and new
are two built-in functions used for memory allocation, but they serve different purposes and are used in different contexts. Understanding the distinction between make
and new
is crucial for effective memory management and data structure initialization in Go. This guide explains the differences between make
and new
, including their uses, syntax, and practical examples.
new
FunctionThe new
function in Go is used to allocate memory for a variable and returns a pointer to that memory. It initializes the allocated memory with the zero value of the type being allocated.
Syntax
Type
is the type of the value to allocate.pointer
is a pointer to the allocated zero value of Type
.Example
Explanation:
new(int)
allocates memory for an int
and returns a pointer to it.p
points to an int
with a zero value of 0
.Key Points
new
only allocates memory and zeroes it out.make
FunctionThe make
function is used to initialize slices, maps, and channels. Unlike new
, make
not only allocates memory but also initializes the underlying data structure, making it ready for use.
Syntax
slice
: Initializes a slice with a specified length and capacity.map
: Initializes a map with the specified key and value types.channel
: Initializes a channel with a specified buffer size.make
with a SliceExplanation:
make([]int, 3, 5)
creates a slice with 3 elements, each initialized to zero, and a capacity of 5.make
with a MapExplanation:
make(map[string]int)
creates a map ready for storing key-value pairs with string keys and int values.make
with a ChannelExplanation:
make(chan int, 2)
creates a buffered channel that can hold up to 2 int
values.Key Points
make
initializes and returns an initialized data structure.Feature | new Function | make Function |
---|---|---|
Usage | Allocates memory and returns a pointer. | Initializes and returns an initialized data structure. |
Types | Basic types (e.g., int, float64, struct). | Slices, maps, channels. |
Initialization | Initializes memory to zero value. | Initializes underlying data structure, not zero. |
Return Type | Returns a pointer to the allocated value. | Returns the data structure itself. |
Example |
In Go, the new
function and make
function are both essential for memory allocation, but they serve different purposes. The new
function is used for allocating memory and returning a pointer to a zeroed value, while the make
function is specifically for initializing slices, maps, and channels, setting them up for immediate use. Understanding when and how to use each function helps in writing more efficient and effective Go code.