Go switch语句实例

switch语句表达式条件可跨多个分支条件语句。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

这里有一个基本的switch语句用法。可以在同一个case语句中使用逗号分隔多个表达式。 在这个例子中也使用可选的 default 情况。

无表达式的switch语句是表达if/else逻辑的替代方式。这里还显示了case表达式可以为非常量数据。

类型switch比较的是类型而不是值。可以使用它来发现接口值的类型。在这个例子中,变量t将具有对应于其子句的类型。

switch.go的完整代码如下所示 -


package main

import "fmt"
import "time"

func main() {

    // Here's a basic `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")
    }

    // You can use commas to separate multiple expressions
    // in the same `case` statement. We use the optional
    // `default` case in this example as well.
    switch time.Now().Weekday() {
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend")
    default:
        fmt.Println("It's a weekday")
    }

    // `switch` without an expression is an alternate way
    // to express if/else logic. Here we also show how the
    // `case` expressions can be non-constants.
    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("It's before noon")
    default:
        fmt.Println("It's after noon")
    }

    // A type `switch` compares types instead of values.  You
    // can use this to discover the the type of an interface
    // value.  In this example, the variable `t` will have the
    // type corresponding to its clause.
    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")
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run switch.go
Write 2 as two
It's the weekend
It's after noon
I'm a bool
I'm an int
Don't know type string

上一篇:Go if/else语句实例

下一篇:Go切片实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程