go 的一些例子
go 的 switch–case
switch–case 走的逻辑 或者说流程 和 c/c++ 是一样的,自上而下,判断case 是否满足条件
如果满足条件,进入相应的语句,如果不满足,走 default
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Hello, 世界")
i := 5
fmt.Println("write ", i, " as ")
switch i {
case 1:
fmt.Print("one")
case 2:
fmt.Print("two")
case 3:
fmt.Print("three")
default:
fmt.Print("else")
}
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println(" this is weekend", time.Now().Weekday())
default:
fmt.Println(" this is weekday", time.Now().Weekday())
}
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("this is before noon", time.Now().Hour())
default:
fmt.Println("this is after noon", time.Now().Hour())
}
whatAmI := func(i interface{
}) {
switch t := i.(type) {
case bool:
fmt.Println("this is a bool")
case int:
fmt.Println("this is a int")
case string:
fmt.Println("this is a string")
// 为什么 吧 default 写在最后?因为 t 会依次从bool 到 string 比较, 不满足当前的,就比较下一个,直到 default ,如果说 case 无穷, 如果一直没匹配到,那么这就是一个死循环了
default:
fmt.Println("Don't know this type", t)
}
}
whatAmI(true)
whatAmI(123)
whatAmI("zhangbuda")
whatAmI(2.22)
}
# 输出结果
Hello, 世界
write 5 as
else this is weekday Tuesday
this is after noon 23
this is a bool
this is a int
this is a string
Don't know this type 2.22
这里插播一下 关于 go 获取当前时间
import