switch
语句表达式条件可跨多个分支条件语句。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.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