Go语言学习笔记(3)——分支、循环结构

1 条件语句: if, else if, else
   特殊用法:判断num是奇是偶;其中局部变量num只能在该if...else语句中使用

  if num := 10; num % 2 == 0 {
              fmt.Println(num, "is even.")    //偶
  } else {
              fmt.Println(num, "is odd.")     //奇
  }    

                                        
2 switch语句,以下是其在Go中所有特殊用法及说明:

 switch x := 5; x{              //switch后可以没有表达式!
              default:
                          fmt.Println(x)    //default项并不一定放在最后位置(可以省略),其作用是
                                            //当所有case都匹配失败后,自动匹配default.
              case 5:
                          x += 10
                          fmt.Println(x)
                          fallthrough       //Go中默认每个case后都自带一个break;
                                            //如果想要匹配成功后还继续执行下面的case,
                                            //则需要在此case的最后一行加上fallthrough
              case 6,7,8:                   //一个case后可以跟多个值
                          x += 20
                          fmt.Println(x)
              case :                    //case后的表达式可以省略,认为是switch true,(为啥我省略的就ERROR!)
                                        //并且每个case表达式都被计算为true,并执行相应的代码块。
                          x += 30
                          fmt.Println("哈哈")
}    


  type-switch: switch也可以被用来判断某个interface变量中实际存储的变量类型     

var x interface{}
switch x.(type) {             //switch i := x.(type)
         case type1:
                       语句1
         case type2:
                       语句2
}

                
3 select 语句 (类似于switch语句)         

var c1, c2, c3 chan int
var i1, i2 int
                         
select {
          case i1 = <- c1:
                           fmt.Printf("Received ", i1, "from c1
")
          case c2 <- i2:
                           fmt.Printf("Sent ", i2, "to c2
")
          case i3, ok := (<- c3):          //i3, ok := <- c3
                           if ok {
                                  fmt.Printf("Received ", i3, "from c3
")
                           } else  {
                                  fmt.Printf("c3 is closed
")
                           }
          default:
                           fmt.Printf("No communication.
")
}

每个case都必须是一个通信!所有channel表达式和被发送的都会被求值!    
如果某个通信可以进行,则执行,其他case就被忽略。如果多个case都可执行,则会随机公平地选出一个执行!
否则:如果有default语句,则执行default;如果没有default,则select将阻塞,直到某个通信可以执行!
    
4 循环语句: for是唯一的循环语句!且for循环中的初始化语句、条件判断语句和条件改变语句都是可选的。                 

     for i := 0; i <= 10; i++{
              fmt.Printf(" %d", i)
     }

   for循环的range格式可以对slice、map、数组和字符串等进行循环迭代:

    for key, value := range oldMap {
              newMap[key] = value        //数组复制。。。。。。
    }  

*跳出循环: break, continue, goto( 使用goto + 自定义标识符,可以无条件地转到以该标识符开头的行!)

///纵有疾风起,人生不言弃///
原文地址:https://www.cnblogs.com/skzxc/p/10664529.html