写在前面
- map就是key-value对的数据结构,
- 而有关函数,像C/C++中,有函数指针,像javascript有闭包,Go也一样
map
- map是一种key-value结构
- 想象一下,如果数组的下标不再规定是数字,而是可以用string类型甚至更复杂的类型,那样会不会灵活许多
- 而map正是提供了这种可能
- 一个空的map,它的值为nil。一个nil的map是没有key的,也不能加入key
- 可以用make函数来创建map
m := make(map[string]int)
m["apple"] = 5
m["pen"] = 7
package main
import "fmt"
type vertex struct {
x,y int
}
var m = map[string]vertex{
"home": vertex{0, 0},
"school": vertex{1,1},
}
func main() {
fmt.Println(m)
}
package main
import "fmt"
type vertex struct {
x,y int
}
var m = map[string]vertex{
"home": {0, 0},
"school": {1,1},
}
func main() {
fmt.Println(m)
}
m := make(map[string]int)
m["apple"] = 2
m := make(map[string]int)
m["apple"] = 2
temp = m["apple"]
m := make(map[string]int)
m["apple"] = 2
delete(m, "apple")
m := make(map[string]int)
m["apple"] = 2
elem, ok := m["apple"] //在能找到相应值的时候elem为相应的value,ok为true;否则,elem为相应的零值,而ok为false
函数的特殊用法
- 函数其实也是一种值,在C/C++中是一种指针
- 函数作为值,也可以像其它变量一样,作为返回值等
- 以下直接用官方例子
package main
import (
"fmt"
"math"
)
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))
}
package main
import "fmt"
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),
)
}
}
- 什么是闭包呢?抛弃那些复杂的定义,运行上述例子,观测
- 不难发现,上述例子中的adder里的sum像是全局变量,通过pos和neg都能改变它
- 且pos和neg访问的是相互独立的sum
- 每次调用pos或者neg,都不会让sum归零,而这接着上次使用的值继续运行!
- 官方教程原话:Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.