05 | 程序结构

条件判断

  • 条件表达式结果必须是布尔值
  • 支持变量赋值
if var declaration; condition{

}
  • 常用场景
if v,err = someFun();err != nil{

}else{

}
//调用某函数,正确做啥事,错误做啥事

switch

  • case 表达式不限制为常量或整数
  • case 表达式为多个时,用,隔开
  • 不需要break来明确退出case
func TestSwitch(t *testing.T){
    for i:=0; i<5; i++ {
        switch i {
        case 0,2:
            t.Log("0 or 2")
        case 1,3:
            t.Log("1 or 3")
        default:
            t.Log(i)
        }
    }
}
  • fallthrough

循环

go 语言的循环只有for 关键字

  • while
func TestWhile(t *testing.T)  {
    n := 0
    for n < 5 {
        t.Log(n)
        n++
    }
}
  • while(true)
func TestWhile(t *testing.T)  {
    for   {
        t.Log("hello world\n")
    }
}
  • for
func TestFor(t *testing.T){
    for i:=0; i<5; i++ {
        t.Log(i)
    }
}

其他

  • break continue 支持标记
  • goto
  • select

你可能感兴趣的:(05 | 程序结构)