循环
for i = 0; i <= 10; i++ {
}
条件循环
package loop_test
import "testing"
func TestWhileLoop(t *testing.T) {
n := 0
for n < 5 {
t.Log(n)
n++
}
}
无限循环
for {
...
}
Go语言仅支持for循环
if条件
if condition {
...
} else {
...
}
if condition {
...
} else if condition {
...
} else {
...
}
- condition 必须为bool值
- 支持变量赋值
if var declaration; condition {
...
}
if v,err = someFunc(); err == nil {
...
} else {
...
}
package condition_test
import "testing"
func TestIfMultiSec(t *testing.T) {
if a := 1 == 1; a {
t.Log("1 == 1")
}
}
switch条件
switch os := runtime.GOOS;os {
case "str1":
...
case "str2":
...
default:
...
}
switch {
case bool1:
...
case bool2:
...
case bool3:
...
}
package condition_test
import "testing"
func TestIfMultiSec(t *testing.T) {
if a := 1 == 1; a {
t.Log("1 == 1")
}
}
func TestSwitch(t *testing.T) {
for i:=0;i<5;i++{
switch i {
case 0,2:
t.Log("Even")
case 1,3:
t.Log("Odd")
default:
t.Log("It is not 0-3")
}
}
}
func TestSwitchIfLike(t *testing.T) {
for i:=0;i<5;i++{
switch {
case i % 2 == 0:
t.Log("Even")
case i % 2 == 1:
t.Log("Odd")
default:
t.Log("unknown")
}
}
}
- switch 条件表达式不限制为常量或整数
- 单个case中,可以出现多个结果选项,使用逗号分隔
- 与C语言等规则相反,Go语言不需要用break来明确退出一个case
- 可以不设定switch之后的条件表达式,在此种情况下,整个switch结构与多个if...else...的逻辑作用相同
网友评论