初识Go(2)

1.if
Go 的 if 还有一个强大的地方就是条件判断语句里面允许声明一个变量,这个变量的作用域
只能在该条件逻辑块内,其他地方就不起作用了,如下所示
// 计算获取值 x,然后根据 x 返回的大小,判断是否大于 10。
if x := computedValue();x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}

多个条件的时候如下所示:
if integer == 3 {
fmt.Println("The integer is equal to 3")
} else if integer < 3 {
fmt.Println("The integer is less than 3")
} else {
fmt.Println("The integer is greater than 3")
}

2.for
for index:=0; index < 10 ; index++ {
sum += index
}

sum := 1
for sum < 1000 {
sum += sum
}  // while

for 配合 range 可以用于读取 slice 和 map 的数据:
for k,v:=range map {
fmt.Println("map's key:",k)
fmt.Println("map's val:",v)
}

由于 Go 支持“多值返回”, 而对于“声明而未被调用”的变量, 编译器会报错, 在这种情况下, 
可以使用_来丢弃不需要的返回值 例如
for _, v := range map{
fmt.Println("map's val:", v)
}

3.switch
i := 10
switch i {
case 1:
fmt.Println("i is equal to 1")
case 2, 3, 4:
fmt.Println("i is equal to 2, 3 or 4")
case 10:
fmt.Println("i is equal to 10")
default:
fmt.Println("All I know is that i is an integer")
}

同时,Go 里面 switch 默认相当于每
个 case 最后带有 break,匹配成功后不会自动向下执行其他 case,而是跳出整个 switch, 
但是可以使用 fallthrough 强制执行后面的 case 代码。

  

posted @ 2014-12-23 16:49  huangxiaohen  阅读(156)  评论(0编辑  收藏  举报