Golang中for循环是唯一循环结构,支持标准三段式、仅条件和无限循环;break用于终止循环,可配合标签跳出外层循环;continue跳过当前迭代,也可结合标签控制嵌套循环流程,合理使用能提升代码效率与可读性。

在Golang中,for循环是唯一支持的循环结构,它功能强大且灵活。结合break和continue语句,可以精确控制程序流程。下面详细介绍它们的用法及常见场景。
基本for循环语法
Golang中的for循环有多种写法:
- 标准三段式:for 初始化; 条件; 增量 { ... }
- 仅条件式:for 条件 { ... }
- 无限循环:for { ... }
例如:
for i := 0; i
使用break跳出循环
break用于立即终止当前循环,常用于满足特定条件时提前退出。
示例:查找数组中第一个负数并停止遍历
nums := []int{1, 3, 7, -2, 8, -5}
for _, v := range nums {
if v
<p>输出到-2即停止,后续元素不再处理。</p>
<p>在嵌套循环中,break只跳出最内层循环。若需跳出外层,可使用标签:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig"><img
src="https://img.php.cn/upload/skill/000/000/081/179215391842073.jpg" alt="Golang Uber Dig" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig" class="overflowclass">Golang Uber Dig</a>
<p class="overflowclass">使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等</p>
</div>
<a rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<font face="Courier New">
<pre class="brush:php;toolbar:false;">
outer:
for i := 0; i
使用continue跳过当前迭代
continue会跳过本次循环剩余代码,直接进入下一次迭代。
常用于过滤不符合条件的数据:
for i := 0; i
上述代码跳过所有偶数,只输出奇数。
同样,continue也可配合标签用于嵌套循环:
outer: for i := 0; i
当j为1时,跳转到外层循环的下一轮,避免执行内层剩余逻辑。
基本上就这些。掌握for、break和continue的组合使用,能让循环逻辑更清晰高效。注意标签的使用要适度,避免降低代码可读性。
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










