流程控制

流程控制 #

判断语句 if #

基本语法

  • if 后没有小括号
  • 支持变量初始化,初始化的变量要以 “;” 结尾
  • 使用变量初始化产生的变量,作用域仅在 if 语句之内
if 1 < 2 {
    fmt.Println(1) //1
}
if a := 5; a > 3 {	//变量初始化 a
    fmt.Println(a) //5
}
//fmt.Println(a)	超出作用域

循环语句 for #

for 语句有三种形式

第一种

a := 1
for {
    a++
    if a > 3 {
        break
    }
    fmt.Print(a, ":") //2:3:
}

第二种

a = 1
for a < 3 {
    a++
    fmt.Print(a, ":") //2:3:
}

第三种

a = 1
for i := 0; i < 3; i++ {
    a++
    fmt.Print(a, ":") //2:3:4:
}

跳转语句 #

分为三种

  • goto
  • break
  • continue

以上三种均支持与标签的结合使用

switch #

特点

  • 接受任何类型
  • 不需要 break,默认不会继续执行下一个 case。如果想继续下一个 case,需要调用 fallthrough
  • 支持初始化表达式,初始化表达式右边需要加分号

第一种

str := "world"
switch str {
case "hello":
  fmt.Println(1)
case "world":
  fmt.Println(2)
default:
  fmt.Println(3)
}
//output: 2

第二种

switch a := 5; {
case a == 1:
  fmt.Println("a")
case a > 3:
  fmt.Println("b")
  fallthrough
case a > 4:
  fmt.Println("c")
}
//output: b c
沪ICP备17055033号-2