Go by Example: Switch

codemanship · · 1202 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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。

英文原文



有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:codemanship

查看原文:Go by Example: Switch

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1202 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传