Both methods are built-in and used for memory allocation and initialization of types.
new()
- Allocates zeroed storage for a variable of the specified type (“zeroed memory” refers to a block of memory that has all of its bits set to zero)
- Initializes it to the zero value of the type, e.g. 0 or an empty string.
- Returns a pointer to the newly allocated value
new()can be used for all types of data, even simple types like integers- Can be used with the
varkeyword and short assignment:= - Usually used for types like structs
max := new(Person)
fmt.Println(max)In the example above, this will print a pointer to the empty struct: &{ 0}.
Values
new()can be used with both the varkeyword and the shortcut for variable initialization:
var people = new(map[string]Person)
// or:
people := new(map[string]Person)make()
Compared to new()it can be only used for Go’s built-in types slices, maps and channels. make()does not only allocate memory, but also initialize the underlying data structure:
- For slices,
makeallocates an array of the specified type and size, and returns a slice reference to this array. This reference includes the length and capacity of the slice. - For maps,
makeinitializes the hash map structure. - For channels,
makesets up the channel’s data buffer and control structures.
make()can also be used with both the varkeyword and the short assignment :=.
var people = new(map[string]Person)
// or:
people := new(map[string]Person)Next chapter: Packages and Package Management