007_go语言中的switch语句

代码演示

package main

import "fmt"
import "time"

func main() {
	i := 2
	fmt.Print("write ", i, " as ")
	switch i {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	}

	switch time.Now().Weekday() {
	case time.Saturday, time.Sunday:
		fmt.Println("It's the weekend")
	default:
		fmt.Println("It's a weekday")
	}

	t := time.Now()
	switch {
	case t.Hour() < 12:
		fmt.Println("It's before noon")
	default:
		fmt.Println("It's after noon")
	}

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

代码运行结果

write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

代码解读:

  • switch声明的表达式通过条件来去往多个分支执行语句
  • 第一个部分的经典的switch表达式
  • 也可以用逗号来分割多个条件语句
  • 如果switch后面没有跟上条件表达式,那么就相当于另一个if/else的表达式变形
  • 一个类型方式的switch可以用类型来替代值。可以用这个方式来发现接口的类型。
posted @ 2018-03-28 19:06  Joestar  阅读(123)  评论(0编辑  收藏  举报