Golang语法基础:使用Switch

4年以前  |  阅读数:149 次  |  编程语言:Golang 

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")
    }

    // 类型开关 (`type switch`) 比较类型而非值。可以用来发现一个接口值的
    // 类型。在这个例子中,变量 `t` 在每个分支中会有相应的类型。
    whatAmI := func(i interface{}) {
        switch t := i.(type) {
        case bool:
            fmt.Println("I'm a bool")
        case int:
            fmt.Println("I'm an int")
        default:
            fmt.Printf("Don't know type %T\n", t)
        }
    }
    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")
}
 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
将二进制数据转为16进制以便显示
获取IMSI
获取IMEI
Java生成UUID
PHP自定义函数获取搜索引擎来源关键字的方法
让你成为最历害的git提交人
在Zeus Web Server中安装PHP语言支持
指定应用ID以获取对应的应用名称
再谈PHP中单双引号的区别详解
Python 2与Python 3版本和编码的对比
php+ajax+json 详解及实例代码
Yii2汉字转拼音类的实例代码
php封装的page分页类完整实例
php数组合并array_merge()函数使用注意事项
PHP实现简单爬虫的方法
PHP设计模式之工厂模式与单例模式
php实现数组中索引关联数据转换成json对象的方法
wget使用技巧