Hoping to understand maps in Go better.
Given this code:
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m []map[string]Vertex
var m1 map[string]Vertex
func main() {
m = make([]map[string]Vertex, 3)
m1 = make(map[string]Vertex)
m1["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
m = append(m, m1)
fmt.Println(m)
fmt.Println(len(m))
fmt.Println(m[3]["Bell Labs"])
}
I get an output of
[map[] map[] map[] map[Bell Labs:{40.68433 -74.39967}]]
4
{40.68433 -74.39967}
Why is it that the first 3 elements in the array are empty/null maps, shouldn't it print out [map[Bell Labs:{40.68433 -74.39967}]]
instead?
Why is it that the first 3 elements in the array are empty/null maps?
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, n) slice slice of type T with length n and capacity n make(T, n, m) slice slice of type T with length n and capacity m
The slice m
of map
m = make([]map[string]Vertex, 3)
is equivalent to
m = make([]map[string]Vertex, 3, 3)
it should be
m = make([]map[string]Vertex, 0, 3)
For example,
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m []map[string]Vertex
var m1 map[string]Vertex
func main() {
m = make([]map[string]Vertex, 0, 3)
fmt.Println(len(m), cap(m))
m1 = make(map[string]Vertex)
m1["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
m = append(m, m1)
fmt.Println(m)
fmt.Println(len(m), cap(m))
fmt.Println(m[0]["Bell Labs"])
}
Playground: https://play.golang.org/p/i9f0rrCrtY_5
Output:
0 3
[map[Bell Labs:{40.68433 -74.39967}]]
1 3
{40.68433 -74.39967}