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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With