### Maps
A map maps key to values.
type Vertex struct { Lat, Long float64 } var m map[string]Vertex func main(){ m = make(map[string]Vertex) m["Bell Labs"] = Vertex{ 40.68433, -74.39967, } fmt.Println(m["Bell Labs"]) }
– Map leterals
Map literals are like struct literals, but the keys are requried
type Vertex struct { Lat, Long float64 } var m = map[string]Vertex{ "Bell Labs" : Vertex{ 40.68433, -74.39967, }, "Google": Vertex { 37.42202, -122.08408, }, } func main(){ fmt.Println(m) }
– Map literals continued
If the top-level type is just a type name, you can omit it from the elements of the literal.
– Mutating Maps
Insert, Retrieve, Delete
func main(){ m := make(map[string]int) m["Answer"] = 42 fmt.Println("The value:", m["Answer"]) m["Answer"] = 48 fmt.Println("The value:", m["Answer"]) delete(m, "Answer") fmt.Println("The value:", m["Answer"]) v, ok := m["Answer"] fmt.Println("The value:", v, "Present?", ok) }
### Function values
Functions are values too. They can be passed around just like other values. Function values may be used as function arguments and return values.
func compute(fn func(float64, float64) float64) float64 { return fn(3, 4) } func main(){ hypot := func(x, y float64) float64 { return math.Sqrt(x*x + y*y) } fmt.Println(hypot(5, 12)) fmt.Println(compute(hypot)) fmt.Println(compute(math.Pow)) }
– Function closures
A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables.
func adder() func(int) int { sum := 0 return func(x int) int { sum += x return sum } } func main(){ pos, neg := adder(), adder() for i := 0; i<10; i++ { fmt.Println( pos(i), neg(-2*i), ) } }
$ go build hello.go && ./hello
0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90
うむ、GoにもなるとTutorialのレベルが高いな