go | switch/case、array、slices、range、functions

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值