05-循环

28 阅读1分钟

循环

Go语言仅支持循环关键字for

代码示例

// 实现while循环
n := 0
for n < 5{
    n++
    fmt.Println(n)
}
// 实现无限循环
n := 100
for {
    fmt.Println(n)
}

if条件语句

if condition{
    // code to be executed if condition is ture
} else {
    // code to be executed if condition is false
}
if condition - 1 {
        // code to be executed if condition-1 is ture
} else if condition - 2 {
        // code to be executed if condition-2 is ture
} else {
        // code to be executed if both condition-1 and condition-2 are false
}
  1. cindition表达式结果必须是布尔值
  2. 支持变量赋值
if var declaration; condition {
    // code to be executed if conditin is true
}

switch条件

switch os := runtime.GOOS; os {
case "darwin":
    t.Log("OS X")
    // break
case "linux":
    t.Log("Linux.")
default:
    // freebsd, openbsd
    // plan9, windows
    t.Logf("%s", os)
}
switch {
case 0 <= Num && Num <=3:
    fmt.Print("0-3")
case 4 <= Num && Num <=6:
    fmt.Print("4-6")
case 7 <= Num && Num <=9:
    fmt.Print("7-9")
}
  1. 条件表达式不限制为常量或者整数
  2. 单个case中,可以出现多个结果选项,使用逗号分隔
  3. 与C语言等规则相反,Go语言不需要用break来明确退出一个case
  4. 可以不设定switch之后的条件表达式,在此种情况下,整个switch结构与多个if...else...的逻辑相同