Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between make(map) and map{}

Tags:

go

Just wondering what the difference is between:

z := make(map[*test] string)

and

z := map[*test] string{}

am I imagining things or are they both not valid?

like image 626
Alexander Mills Avatar asked Dec 01 '18 22:12

Alexander Mills


People also ask

What is the difference between make ()` and new ()` in Golang?

new() vs make() Note that make() can only be used to initialize slices, maps, and channels, and that, unlike the new() function, make() does not return a pointer.

Why do we use make in Golang?

In Golang, make() is used for slices, maps, or channels. make() allocates memory on the heap and initializes and puts zero or empty strings into values. Unlike new() , make() returns the same type as its argument. Slice: The size determines the length.

How do you initialize a map in Golang?

Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.

How do you initialize an empty map in Golang?

To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.


1 Answers

The Go Programming Language Specification

Making slices, maps and channels

The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values.

Call         Type T  Result
make(T)      map     map of type T
make(T, n)   map     map of type T with initial space for approximately n elements

Composite literals

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.

map[string]int{}
map[string]int{"one": 1}

make is the canonical form. Composite literals are a convenient, alternate form.

z := make(map[int]string)

and

z := map[int]string{}

are equivalent.

like image 127
peterSO Avatar answered Sep 21 '22 11:09

peterSO