Go语言基础之流程控制

if else(分支结构)

go 复制代码
if score := 65; score >= 90 {  //声明并初始化变量 score 为 65
    fmt.Println("A")
} else if score > 75 {
    fmt.Println("B")
} else {
    fmt.Println("C")
}
 

for(循环结构)

go 复制代码
for i := 0; i < 10; i++ {
    fmt.Println(i)
}
 
go 复制代码
for ; i < 10; i++ {
    i := 0
    fmt.Println(i)
}
 

for range(键值循环)

go 复制代码
for i := range 5 {
    fmt.Println(i)
}
 
0
1
2
3
4

switch case

fallthrough语法可以执行满足条件的case的下一个case,是为了兼容C语言中的case设计的。

css 复制代码
func switchDemo5() {
	s := "a"
	switch {
	case s == "a":
		fmt.Println("a")
		fallthrough
	case s == "b":
		fmt.Println("b")
	case s == "c":
		fmt.Println("c")
	default:
		fmt.Println("...")
	}
}

a
b

goto(跳转到指定标签)

c 复制代码
if (error_condition) {
    goto cleanup;
}
// ...正常逻辑
cleanup:
    // 释放资源
 
c 复制代码
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        if (condition) goto loop_exit;
    }
}
loop_exit:
 

break(跳出循环)

continue(继续下次循环)

相关推荐
喵了几个咪9 小时前
GoWind CMS 拆解:在 Go 里给 TipTap 搭一套 Yjs 协同后端
开发语言·后端·golang
l1t17 小时前
测试用go语言执行脚本把数据保存到SQLite数据库
数据库·golang·sqlite
Agent世界20 小时前
千问Go上线我的应用:一句话生成可部署 AI 软件的技术拆解
开发语言·人工智能·golang·ai智能体
念何架构之路21 小时前
Go reflect包值操作 Value 的读写、可设置性与 interface 布局
开发语言·后端·golang
紧跟先前的步伐1 天前
Go AI Agent 实战 18|Tool Calling 的基本原理与完整执行流程
前端·数据库·人工智能·ai·golang·1024程序员节
紧跟先前的步伐1 天前
Go AI Agent 实战 17|模型适配层设计:让模型可替换
开发语言·人工智能·后端·ai·golang
l1t1 天前
DeepSeek辅助编写连接sqlite的CLI
数据库·golang·sqlite
计算机就业还在扩大1 天前
第2期-cmp.Ordered+类型推断+刻意未支持的特性
后端·面试·golang
念何架构之路2 天前
Go reflect 包:结构体反射 —Field、Tag 与 VisibleFields
java·数据库·golang