您的位置:首页 > 运维架构 > Docker

[Go语言]从Docker源码学习Go——if语句和map结构

2014-08-19 20:00 1291 查看

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(map[string]func())

...

// 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[os.Args[0]]
if exists {
initializer()

return true
}

return false
}


可以看到registeredInitializers是一个map类型,键类型为string,值类型为func().

map的初始化是通过make()来进行, make是go的内置方法。

除了通过make, 还可以通过类似下面的方法进行初始化

mapCreated := map[string]func() int {
1: func() int {return 10},
2: func() int {return 20},
3: func() int {return 30},
}


继续通过代码看map的使用

initializer, exists := registeredInitializers[os.Args[0]]


map[keyvalue]返回两个值,先看第二个,代表是否存在,第一个是在存在的情况下取得value的值,此处也就是取得这个func().

再后面的代码就是判断是否存在,如果存在就执行取得的func().

如果我们不想取value的值,只想判断是否存在,可以通过加下划线_的方式来忽略返回,比如

_, exists := xxx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: