zoukankan      html  css  js  c++  java
  • go语言从例子开始之Example7.switch分支结构

    switch ,方便的条件分支语句

    package main
    import "fmt"
    import "time"
    func main() {
    一个基本的 switch。
    
        i := 2
        fmt.Print("write ", i, " as ")
        switch i {
        case 1:
            fmt.Println("one")
        case 2:
            fmt.Println("two")
        case 3:
            fmt.Println("three")
        }
    在一个 case 语句中,你可以使用逗号来分隔多个表达式。在这个例子中,我们很好的使用了可选的default 分支。
    
        switch time.Now().Weekday() {
        case time.Saturday, time.Sunday:
            fmt.Println("it's the weekend")
        default:
            fmt.Println("it's a weekday")
        }
    不带表达式的 switch 是实现 if/else 逻辑的另一种方式。这里展示了 case 表达式是如何使用非常量的。
    
        t := time.Now()
        switch {
        case t.Hour() < 12:
            fmt.Println("it's before noon")
        default:
            fmt.Println("it's after noon")
        }
    }

    Result:

    $ go run switch.go 
    write 2 as two
    it's the weekend
    it's before noon

    坐标: 上一个例子     下一个例子

  • 相关阅读:
    min_25筛入门
    [湖南集训]更为厉害/谈笑风生
    [ARC060D] 最良表現
    [CQOI2007]矩形
    [SCOI2009]粉刷匠
    PAT乙级1030
    PAT乙级1028
    PAT乙级1029
    PAT乙级1026
    PAT乙级1027
  • 原文地址:https://www.cnblogs.com/yhleng/p/11726638.html
Copyright © 2011-2022 走看看