package main
import \"fmt\"
func main() {
p := new(map[string]int)
m := make(map[string]int)
m[\"in m\"] = 2
(*p)[\"in p\"] = 1
fmt.Println(m)
Both new
and make
are used to allocate memory in a program, but they work differently. new(T, args)
zeros memory and returns the memory address (a value of type *T
) but does not initialize that memory. make(T, args)
on the other hand initializes a value of type T
. A map need to be initialized because, while a map can be empty, there is still the structure of the map itself, which is non-zero and therefore needs to be initialized before use.
From Effective Go:
The built-in function make(T, args) serves a purpose different from new(T). It creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of type T (not *T). The reason for the distinction is that these three types represent, under the covers, references to data structures that must be initialized before use. A slice, for example, is a three-item descriptor containing a pointer to the data (inside an array), the length, and the capacity, and until those items are initialized, the slice is nil. For slices, maps, and channels, make initializes the internal data structure and prepares the value for use.