首页 > 其他 > 详细

Go by Example: Switch

时间:2014-11-26 22:43:32      阅读:349      评论:0      收藏:0      [点我收藏+]

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语句。
    // 当上面的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")
    }
}
输出

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

下一个例子:  Go by Example: Arrays。

英文原文


Go by Example: Switch

原文:http://blog.csdn.net/codemanship/article/details/41521509

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!