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(继续下次循环)

相关推荐
李燚6 小时前
ReAct 循环的 50 行 Go 实现,逐行拆解
javascript·人工智能·react.js·golang·aigc·agent
念何架构之路8 小时前
Go pprof性能剖析
开发语言·后端·golang
姚不倒9 小时前
Go语言实战:构建一个安全的计算器服务(接口、错误处理与Panic恢复)
云原生·golang
XMYX-01 天前
37 - Go env 环境变量:配置管理与运行时控制
开发语言·golang
姚不倒1 天前
Go 进阶实战:实现泛型数据验证器
云原生·golang
XMYX-01 天前
36 - Go exec 执行命令
开发语言·golang
lolo大魔王1 天前
Go 语言 HTTP 协议与 RESTful API 实训全解(理论 + 实战 + 规范)
http·golang·restful
一只小逸白1 天前
LeetCode Go 常用函数速查表
linux·leetcode·golang
LCG元1 天前
【Go后端开发】从 0 到生产级:高性能分布式网关全实现 + 接口限流熔断降级实战
分布式·golang·wpf
姚不倒2 天前
Go语言进阶:接口、错误处理与并发编程(goroutine/channel/context)
云原生·golang