Go中的结构控制与C有许多相似之处,但其不同之处才是独到之处。Go不再使用 do
或 while
循环,只有一个更通用的for
;switch
要更灵活一点;if
和switch
像 for
一样可接受可选的初始化语句;此外,还有一个包含类型选择和多路通信复用器的新控制结构:select
。其语法也有些许不同:没有圆括号,而其主体必须始终使用大括号括住。
1. if语句
if x > 0 {
return y
}
if a := 0 ; a < 0 {
return y
}else if a == 0 {
return y
}else{
return y
}
2.switch语句 . Go的 switch
比C的更通用。其表达式无需为常量或整数,case
语句会自上而下逐一进行求值直到匹配为止。若 switch
后面没有表达式,它将匹配true
,因此,我们可以将 if-else-if-else
链写成一个switch
,这也更符合Go的风格。
switch x {
case 0 :
return y
case 1 :
return y
}
2.1switch
并不会自动下溯,但 case
可通过逗号分隔来列举相同的处理条件。
func shouldEscape(c byte) bool { switch c { case ' ', '?', '&', '=', '#', '+', '%': return true } return false }2.2
switch
也可用于判断接口变量的动态类型。如
类型选择通过圆括号中的关键字
type
使用类型断言语法。若
switch
在表达式中声明了一个变量,那么该变量的每个子句中都将有该变量对应的类型。
var t interface{} t = functionOfSomeType() switch t := t.(type) { default: fmt.Printf("unexpected type %T", t) // %T 输出 t 是什么类型 case bool: fmt.Printf("boolean %t\n", t) // t 是 bool 类型 case int: fmt.Printf("integer %d\n", t) // t 是 int 类型 case *bool: fmt.Printf("pointer to boolean %t\n", *t) // t 是 *bool 类型 case *int: fmt.Printf("pointer to integer %d\n", *t) // t 是 *int 类型 }3.for循环 Go的
for
循环类似于C,但却不尽相同。它统一了
for
和
while
,不再有
do-while
了。它有三种形式,但只有一种需要分号。
// 如同C的for循环 for init; condition; post { } // 如同C的while循环 for condition { } // 如同C的for(;;)循环 for { }
例:
for x := 0; x < 10 ; x ++ {
}
3.1 若你想遍历数组、切片、字符串或者映射,或从信道中读取消息,range
子句能够帮你轻松实现循环。
m := [3]int{0,1,2}
for n := range m {
fmt.Println(n)
}
sum := 0 for _, value := range array { sum += value }