阿里云优惠券领取

Go语言条件语句

Go语言条件语句
    • if 语句
      • 语法:布尔表达式可以是多个的组合,布尔表达式可以用括号括起来,也可以不用括起来
                     if 布尔表达式{
                /* 在布尔表达式为true时执行 */
                     }
      • 实例
        package main
        import "fmt"
        func main(){
            var a int = 10
            var b int = 50
            if a > 5 && b > 40 {
                  fmt.Printf("a 大于 5,b 大于40\n" )
            }
        }
  • if ... else语句,if嵌套语句,switch语句和其他的语言上没有差别,用法也没啥差别,可以参照上面的if语句。
  • 但是Go语言有和其他语言不同的条件语句 select 语句:select类似于用于通信的switch语句,每个case必须有通讯操作(发送or接收),select随机执行一个可运行的case,如果没有可运行的case,则会阻塞,直到有可运行的case为止,因此,一个默认的case子句是必须的。
  • 语法
        select {
                case communication clause  :
                       statement(s);      
                case communication clause  :
                       statement(s);
                /* 你可以定义任意数量的 case */
                default : /* 可选 */
                       statement(s);
        }
  • 实例
       
 package main
        import "fmt"
        func main() {
                var c1, c2, c3 chan int
                var i1, i2 int
                select {
                    case i1 = <-c1:
                        fmt.Printf("received ", i1, " from c1\n")
                    case c2 <- i2:
                        fmt.Printf("sent ", i2, " to c2\n")
                    case i3, ok := (<-c3):  // same as: i3, ok := <-c3
                        if ok {
                                fmt.Printf("received ", i3, " from c3\n")
                        } else {
                                fmt.Printf("c3 is closed\n")
                        }
                    default:
                        fmt.Printf("no communication\n")
            }
        }
        输出为:no communication
关于 "<-"的用法,可以参考:https://blog.csdn.net/whatday/article/details/74453089
 
posted @ 2018-09-12 17:11  StimmerLove  阅读(390)  评论(0编辑  收藏  举报
hello everybody!!!!!