[Go语言]从Docker源码学习Go——if语句和map结构
if语句继续看docker.go文件的main函数
if reexec.Init() {
return
}
go语言的if不需要像其它语言那样必须加括号,而且,可以在判断以前,增加赋值语句
语法
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
例子
if x := f(); x < y {
return x
} else if x > z {
return z
} else {
return y
}
map结构
继续跟到reexec.Init()方法里面,文件位于docker/reexec/reexec.go
var registeredInitializers = make(mapfunc())
...
// Init is called as the first part of the exec process and returns true if an
// initialization function was called.
func Init() bool {
initializer, exists := registeredInitializers]
if exists {
initializer()
return true
}
return false
}
可以看到registeredInitializers是一个map类型,键类型为string,值类型为func().
map的初始化是通过make()来进行, make是go的内置方法。
除了通过make, 还可以通过类似下面的方法进行初始化
mapCreated := mapfunc() int {
1: func() int {return 10},
2: func() int {return 20},
3: func() int {return 30},
}
继续通过代码看map的使用
initializer, exists := registeredInitializers]
map返回两个值,先看第二个,代表是否存在,第一个是在存在的情况下取得value的值,此处也就是取得这个func().
再后面的代码就是判断是否存在,如果存在就执行取得的func().
如果我们不想取value的值,只想判断是否存在,可以通过加下划线_的方式来忽略返回,比如
_, exists := xxx
页:
[1]