一. 条件语句
go
语言的循环语句长得像这样:
注意else要和 { 在同一行
if condition {
} else if condition {
} else {
}
//or
if condition {
}
除了这样,还有先执行statement
再判断condition
的语句
if statement; condition {
}
二.选择语句Switch
2.1 普通的Switch
Go
中的Switch
语句形如C语言
:
package main
import (
"fmt"
)
func main() {
finger := 8
switch finger {
case 1:
fmt.Println("Thumb")
case 2:
fmt.Println("Index")
case 3:
fmt.Println("Middle")
case 4:
fmt.Println("Ring")
case 5:
fmt.Println("Pinky")
default: //default case
fmt.Println("incorrect finger number")
}
}
因为Go
语言的特性当然也可以写成switch finger := 8; finger {
,
2.2 多条件的Switch
package main
import (
"fmt"
)
func main() {
letter := "i"
switch letter {
case "a", "e", "i", "o", "u":
fmt.Println("vowel")
default:
fmt.Println("not a vowel")
}
}
这段语句中,不管letter
是a、e、i、o、u
中任意一个字母,都会输出vowel
2.3 无表达式的Switch
Switch
的表达式可以默认,且默认的值是true
,且case
中可以放condition
,若满足true
的条件即可触发.
package main
import (
"fmt"
)
func main() {
num := 75
switch {
case num == 75:
fmt.Println("num is 75")
case num >= 0 && num <= 50:
fmt.Println("num is greater than 0 and less than 50")
case num >= 51 && num <= 100:
fmt.Println("num is greater than 51 and less than 100")
case num >= 101:
fmt.Println("num is greater than 100")
}
}
但此时的num
并不能触发num is greater than 51 and less than 100
,而只是输出了num is 75
。
2.3 fallthrough
使用fallthrough
关键字可以让某个case
执行完后,继续执行,例如:
package main
import (
"fmt"
)
func main() {
num := 75
switch {
case num == 75:
fmt.Println("num is 75")
fallthrough
case num >= 0 && num <= 50:
fmt.Println("num is greater than 0 and less than 50")
case num >= 51 && num <= 100:
fmt.Println("num is greater than 51 and less than 100")
case num >= 101:
fmt.Println("num is greater than 100")
}
}
/* outputs
num is 75
num is greater than 0 and less than 50
*/
三.循环
Go
语言的循环是C风格的,形如这样:
for initialisation; condition; post {
}
刚好对标C语言的:
for (initialisation; condition; post)
{}
当然,go
也支持break
、continue
:
package main
import (
"fmt"
)
func main() {
for i := 1; i <= 20; i++ {
if i % 2 == 0 {
continue
} else if i > 10 {
break
} else {
fmt.Print(i, " ")
}
}
}
/* outputs
1 3 5 7 9
*/