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

相关推荐
geovindu21 分钟前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
kite01212 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
Wang's Blog15 小时前
Go-Zero 项目开发21: 实现离线消息拉取与会话管理
开发语言·后端·golang
FfHUCisI15 小时前
Golang学习-约瑟夫环问题(Josephus Problem)
开发语言·学习·golang
会编程的土豆16 小时前
结构体 struct:用代码描述用户、订单、座位
数据库·mysql·golang
llwszx1 天前
【Java/Go后端手撸原生Agent(第九篇):Plan-and-Execute规划模式——从“走一步看一步“到“先谋后动“】
java·python·golang·agent开发·plan模式·规划执行模式
灯澜忆梦1 天前
GO_网络编程---文件传输实战
网络·golang·php
北冥you鱼1 天前
Go 语言新手扫盲:指针 * 和 & 使用场景详解
开发语言·后端·golang
Wang's Blog2 天前
Go-Zero项目开发17: IM私聊功能实现与消息存储设计
开发语言·后端·golang
名字还没想好☜2 天前
Go 的 select 实战:超时、非阻塞收发与优雅退出的三个套路
开发语言·数据库·golang·go·并发