码迷,mamicode.com
首页 > 其他好文 > 详细

Go by Example: Switch

时间:2014-11-26 22:45:40      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:golang   go语言   go   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语句。
    // 当上面的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

标签:golang   go语言   go   switch   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!