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

相关推荐
ttwuai6 小时前
GoFrame + Vue3 后台管理系统实战:CRUD、权限和菜单如何少写重复代码
golang
大P哥阿豪6 小时前
Go panic & recover:深入Go语言的异常拯救之道
开发语言·后端·golang·go
雨师@17 小时前
go语言项目--实例化(图书管理)--004
开发语言·后端·golang
想你依然心痛1 天前
AtomCode在后端开发中的实战体验:Go微服务从零搭建
开发语言·微服务·golang
开发小程序的之朴1 天前
认识安企CMS - 系统概述
nginx·golang·系统架构
雨师@1 天前
go语言项目--实例化(图书管理)--005
开发语言·后端·golang
Vect__1 天前
Go 数据结构 slice 深度剖析
开发语言·数据结构·golang
geovindu1 天前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式
techdashen1 天前
把正确性藏进类型里:从 Go 的 io.Reader 到 Rust 的 API 设计
网络·golang·rust
必胜刻1 天前
从零搭建全栈博客系统:Go + Vue 3 + Docker 全流程实战
vue.js·docker·golang