6 ms·
Is the documentation of go regarding the 'map' data type and the usage of the function 'make' out of date? Because I can't see any difference in: package
by dan00 13y ago
Is the documentation of go regarding the 'map' data type
and the usage of the function 'make' out of date?
Because I can't see any difference in:
package main
import (
"fmt"
)
func main() {
m1 := map[string]int{}
m1["a"] = 1
fmt.Printf("%d\n", m1["a"])
m2 := make(map[string]int)
m2["b"] = 2
fmt.Printf("%d\n", m2["b"])
}
- pothibo 13y agoI think the 2 are generally equals. make is used when you want to initialize a map, slice, channel with a given size. http://golang.org/ref/spec#Making_slices_maps_and_channels http://golang.org/ref/spec#Making_slices_maps_and_channels
- mseepgood 13y agoBoth are equivalent and none is out of date. The first is just the short-hand literal syntax. Same with &Foo{} and new(Foo).
- jerf 13y agoCompare with: func main() { var m1 map[string]int m1["a"] = 1 fmt.Printf("%d\n", m1["a"]) } http://play.golang.org/p/JJQ7dSZLeA http://play.golang.org/p/JJQ7dSZLeA which yields panic: runtime error: assignment to entry in nil map
- dan00 13y agoWell, but this again works: type pair struct { x, y int } func main() { var p pair fmt.Printf("%d\n", p.x) fmt.Printf("%d\n", p.y) } That's just wrong, that declaration and initialization behaves differently depending on the type.
- zemo 13y agoThe zero value for a map is nil. The zero value for a struct is a valid struct whose fields are all zeroed. So for pair, that would be (0, 0). The zero value for a pointer is nil. If you had said `var p *pair`, then it would be a pointer to pair, and it would be nil, and you would get a nil panic error.
- brnstz 13y agoYou can do: m1 := map[string]int{} m1["a"] = 1
- jerf 13y agoIf I could unilaterally make just one change to Go, I'd adopt C#-style nullable types, and change everything to be nonnullable without the extra sigil (or whatever, I have no passion about the syntax itself, just the feature). This would produce, say, map[string]string vs. map?[string]string. The first would not be permitted to be null, the second would. It would be my choice because unlike a lot of other pet ideas which would radically change Go into a new language, I'm pretty sure this would have hardly any effect... excepting of course to remove the Billion Dollar Mistake from the next up-and-coming language.
- dan00 13y agoWell, I'm more or less a programming language nerd and these kind of things just hurt =). Just try to pass a 'map' or a 'struct' to an other function. The 'map' behaves like passed by reference and the 'struct' behaves like passed by value. If you want to pass a 'struct' by reference than you have to use a pointer to a 'struct'. Seriously? What kind of ad hoc programming language design is this?