loops - 如何在不运行以下脚本的情况下退出循环
问题描述
我想从第二个循环跳到第一个循环(比如休息),但休息后我不想打印fmt.Println("The value of i is", i)
。算法如何?
package main
import "fmt"
func main() {
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
break
} else {
fmt.Println("j = ", j)
}
}
fmt.Println("The value of i is", i)
}
}
解决方案
编辑:你编辑了你的代码,所以这里是编辑后的答案。
要从内部继续外循环(打破内循环并跳过外循环的其余部分),您必须继续外循环。
要使用语句解决外部循环,请continue
使用标签:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
continue outer
} else {
fmt.Println("j = ", j)
}
}
fmt.Println("The value of i is", i)
}
这将输出(在Go Playground上尝试):
j = 0
j = 1
Breaking out of loop
j = 0
j = 1
Breaking out of loop
原答案:
break
总是从最内层循环中断(更具体地说是 a或) for
,因此之后外层循环将继续其下一次迭代。switch
select
如果您有嵌套循环,并且您想从外部循环中断内部循环,则必须使用标签:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
break outer
}
fmt.Println("The value of j is", j)
}
}
这将输出(在Go Playground上尝试):
The value of j is 0
The value of j is 1
Breaking out of loop
推荐阅读
- python - 参数未定义,尽管它已在上面定义
- c - 计算矩阵总和的函数给出错误 - [错误] 数组类型的元素类型不完整
- python-3.x - 如何在Python中循环代码时将函数中的变量附加到列表中
- excel - 粘贴为值而不复制名称范围
- c - 在 C 中输出自守数
- haskell - 有没有一种有效的方法来生成给定 Haskell 中的泛型(尤其是带有 monads)类型签名的函数?
- spring - 启动应用程序时如何在没有任何异常的情况下将 FOP 与 Spring Boot 一起使用?
- sql-server - Sequelize JS - 如何处理 Sequelize 不支持的 SQL Server 数据类型
- windows - 适用于 Windows (GCM) 的 Git 凭据管理器不提示输入凭据?
- angular - 如何从角度服务中获取值并将其插入导出的类中?