Go初级三
✅ Go 初级教程(三):控制结构 —— if、for、switch
我们将带你学习 Go 语言中常用的 控制流程语句,让你的程序能根据条件做出判断、循环处理数据,写出更有逻辑、更智能的代码!
🔹 1. if
语句:条件判断
Go 中的 if
语句和 C/Java 类似,但 不需要括号,且条件必须是布尔表达式。
if x > 10 {fmt.Println("x 大于 10")
} else if x == 10 {fmt.Println("x 等于 10")
} else {fmt.Println("x 小于 10")
}
✅ 小技巧:if
可以带初始化语句(常用在错误处理中):
if v := x * 2; v > 100 {fmt.Println("v 的值是:", v)
}
// 注意:v 只在 if 块内有效
🔹 2. for
循环:唯一的循环结构
Go 只有 for
循环,没有 while
或 do-while
,但可以用 for
实现所有循环逻辑。
(1) 普通 for 循环
for i := 0; i < 5; i++ {fmt.Println("第", i, "次循环")
}
(2) 类似 while 的写法
n := 0
for n < 5 {fmt.Println(n)n++
}
(3) 无限循环(常用于服务监听)
for {fmt.Println("一直运行...")// 记得加 break 或 time.Sleep,否则会卡死
}
(4) 遍历数组/slice/map:使用 range
nums := []int{1, 2, 3, 4, 5}
for index, value := range nums {fmt.Printf("索引: %d, 值: %d\n", index, value)
}// 如果不需要索引,用下划线 _
for _, value := range nums {fmt.Println(value)
}
🔹 3. switch
语句:多分支选择
Go 的 switch
更加灵活,不需要 break,也不会穿透(fallthrough 除外)。
基本用法:
day := "周一"switch day {
case "周一":fmt.Println("开始上班了!")
case "周五":fmt.Println("快到周末了!")
case "周六", "周日":fmt.Println("休息日,放松一下~")
default:fmt.Println("普通的一天")
}
高级用法:不带表达式的 switch(类似 if-else 链)
score := 85switch {
case score >= 90:fmt.Println("优秀")
case score >= 75:fmt.Println("良好")
case score >= 60:fmt.Println("及格")
default:fmt.Println("不及格")
}
特殊关键字:fallthrough
如果你想让 case 继续执行下一个分支,使用 fallthrough
:
switch "a" {
case "a":fmt.Println("匹配 a")fallthrough
case "b":fmt.Println("也会执行这里")
}
// 输出:
// 匹配 a
// 也会执行这里
🔹 4. 实战小例子:判断成绩等级 + 循环输入
package mainimport "fmt"func main() {var score intfor {fmt.Print("请输入成绩(输入 -1 退出):")fmt.Scanf("%d", &score)if score == -1 {fmt.Println("程序结束!")break}switch {case score < 0 || score > 100:fmt.Println("成绩无效!")case score >= 90:fmt.Println("等级:A")case score >= 80:fmt.Println("等级:B")case score >= 70:fmt.Println("等级:C")case score >= 60:fmt.Println("等级:D")default:fmt.Println("等级:F")}}
}
✅ 本篇小结
控制结构 | 用途 |
---|---|
if | 条件判断 |
for | 循环(唯一循环结构) |
switch | 多分支选择,更简洁安全 |
💡 提示:Go 的设计哲学是 简洁、明确、少出错,所以去掉了不必要的括号、强制大括号、自动不穿透 case。
📣 下期预告(Go初级四)
在下一篇文章中,我们将深入 函数(Function) 的世界!学习如何定义函数、多返回值、参数传递、匿名函数和闭包,让你的代码更模块化、更高效!
如果你喜欢这个系列,欢迎继续关注 🌟
有任何问题,也可以留言讨论,我们一起学 Go!🚀