go中new和make的区别?
In Go, new
and make
are both built-in functions that are used to allocate memory, but they work slightly differently.
new
is a function that takes a type as an argument, allocates memory to fit a value of that type, and returns a pointer to the allocated memory. This memory is zeroed, meaning that all of its bits are set to zero.
Here's an example of how you might use new
:
// Create a pointer to a new int
intPtr := new(int)
// Use the pointer to set the value at that memory address
*intPtr = 123
// The value of the original variable is now changed
fmt.Println(*intPtr) // 123
make
, on the other hand, is a function that is used to create and initialize a new value of a specific type, such as a slice, map, or channel. Unlike new
, make
doesn't take a type as an argument; it's a special built-in function that is specific to certain types.
Here's an example of how you might use make
to create a new slice:
// Create a new slice with make
slice := make([]int, 5)
// Set the values in the slice
slice[0] = 1
slice[1] = 2
slice[2] = 3
// The slice now has a length of 5 and a capacity of 5
fmt.Println(len(slice)) // 5
fmt.Println(cap(slice)) // 5
In short, new
is used to allocate memory for a new value, while make
is used to initialize and create a new value of a specific type.