golang变量与条件语句使用示例

1.变量声明与使用

Go 复制代码
//变量声明与使用
	var x1 = 123
	x2 := 456
	fmt.Println(x1, x2)
	var v1, v2, v3 = 2017, 2019, 2022
	fmt.Println(v1, v2, v3)
	v4, v5, v6 := "VS2017", "VS2019", "VS2022"
	fmt.Println(v4, v5, v6)

2.常量声明与使用

Go 复制代码
//常量声明与使用
	const YEAR, MONTH, WEEK = 12, 30, 7
	print("\n", YEAR, MONTH, WEEK, "\n")

3.循环条件语句使用

Go 复制代码
//循环使用
	fmt.Println(">>>>>>>>外部变量循环>>>>>>>>>>>>>")
	i := 10
	for i <= 20 {
		fmt.Println(i)
		i++
	}
	fmt.Println(">>>>>>>>常规循环>>>>>>>>>>>>>")
	for j := 0; j < 10; j++ {
		fmt.Println(j)
	}
	fmt.Println("**********范围循环**********")
	for num := range 10 {
		fmt.Println(num)
	}

4.if条件语句使用

Go 复制代码
//条件中使用多语句
	names := []string{"Apple", "Banana"}
	if name := "Apple"; name == names[0] {
		fmt.Println("===》相等")
	}
	//if多个条件判断
	if a := 10; a > 15 {
		fmt.Println("a>15", a)
	} else if a > 12 {
		fmt.Println("a>12,a<15", a)
	} else {
		fmt.Println("a<12", a)
	}

5.switch条件语句使用

Go 复制代码
//switch语句使用
	//匹配数值条件
	sw := 3
	switch sw {
	case 1:
		fmt.Println("one", sw)
		break
	case 2:
		fmt.Println("two", sw)
		break
	case 3:
		fmt.Println("three", sw)
		break
	default:
		fmt.Println("unknow", sw)
		break
	}
	//匹配日期条件
	switch time.Now().Weekday() {
	case time.Saturday, time.Sunday:
		fmt.Println("休息日")
		break
	case time.Friday:
		fmt.Println("工作日最后一天")
		break
	default:
		fmt.Println("工作日")
		break
	}
	//匹配时间条件
	wh := time.Now().Hour()
	switch wh {
	case 5:
		if wm := time.Now().Minute(); wm >= 30 {
			fmt.Println("准备下班...")
		}
		break
	default:
		fmt.Println("工作中...")
		break
	}
	//函数在表达式中使用
	typeChk := func(i interface{}) {
		switch t := i.(type) {
		case bool:
			fmt.Println("bool:", t)
		case int:
			fmt.Println("int:", t)
		default:
			fmt.Println("not a type:", t)
		}
	}
    //调用函数测试
	typeChk(255)
	typeChk(!false)
	typeChk(m)
相关推荐
Wellijohn17 分钟前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
HarmonSir1 小时前
OpenManus 的架构解析:另一个通用 Agent 的最小内核与扩展边界
后端·架构
hsfxuebao1 小时前
Sandbox(沙箱)到底是什么?
后端
一条Go1 小时前
proto 契约:校验注解、错误码与「文案即接口」
后端·github
狗头大军之江苏分军2 小时前
《潮水漫过十七岁》好久没写了
前端·javascript·后端
苍何2 小时前
用 OiiOii Motion + Opus 5.5 做动画视频,效果猛的离谱
后端
geovindu3 小时前
python:Logistic Regression
开发语言·后端·python·算法
ssshooter3 小时前
Replit 项目本地跑:一份实测过的改造清单
前端·后端·设计模式