乐闻世界logo
搜索文章和话题

What is the difference between the " make " and " new " functions in Go?

1个答案

1

In Go, both make and new are built-in functions used for allocating memory, but they have important differences in their purpose and behavior.

new Function

The new function allocates memory for a new variable of a specified type and returns a pointer to that memory. The newly allocated memory is initialized to the zero value of the type. new can be used for any Go type, including basic types, composite types, pointers, and interfaces.

For example, if you want to create a pointer of type int and initialize it to its zero value, you can use new:

go
ptr := new(int) fmt.Println(*ptr) // Output: 0

make Function

The make function is used exclusively for initializing three reference types in Go: slices, maps, and channels, and returns an initialized (non-zero) value. This is because these types point to data structures that require initialization to function correctly. make not only allocates memory but also initializes related properties, such as the length and capacity of slices, the size of maps, and the buffer size of channels.

For example, to create a slice with an initial capacity, you can use make:

go
s := make([]int, 0, 10) fmt.Println(len(s), cap(s)) // Output: 0 10

Summary

  • new allocates memory and returns a pointer to it, with the memory initialized to the zero value of the type, applicable to all types.
  • make is used for initializing slices, maps, and channels, and performs specific initialization beyond memory allocation, applicable only to these three types.

By utilizing these functions, Go provides a more flexible and efficient approach to memory management.

2024年8月7日 21:55 回复

你的答案