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

相关推荐
geovindu14 小时前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
开发小程序的之朴15 小时前
基于Go语言的企业级CMS系统架构设计与性能分析——以AnQiCMS为例
开发语言·golang·系统架构
初心未改HD17 小时前
Go语言net/http与Web开发:构建高性能HTTP服务
开发语言·golang
memories19817 小时前
Go 语言 Channel(管道/通道)
开发语言·后端·golang
初心未改HD18 小时前
Go语言结构体Struct:内存布局、标签、接收者与内存对齐
开发语言·golang
jieyucx18 小时前
Go 数据结构入门:线性表、顺序表、链表
数据结构·链表·golang
eLIN TECE19 小时前
Golang 构建学习
开发语言·学习·golang
jieyucx20 小时前
# Go 语言指针零基础入门详解
开发语言·后端·golang
周末也要写八哥21 小时前
Golang语言与Rust语言的对比
开发语言·后端·golang
不甘先生21 小时前
Go 四层架构实战:Handler + Service + Repository + Entity(清晰、可控、可演进)
开发语言·架构·golang