英文:
How get index when break was called, in a for-range loop?
问题
代码中的问题是变量 i
在 for
循环中重新声明并赋值,导致在循环结束后,i
的值仍然是初始值 0。要实现你期望的结果,可以将 i
的声明移至循环之前:
arr := []string{"A", "B", "C", "D"}
var i int
for i, s := range arr {
fmt.Println(i, s)
if s == "C" {
break
}
}
fmt.Println(i)
这样,i
就会在循环外部保留其值,输出结果将是:
0 A
1 B
2 C
2
这样你就可以在循环外部访问到正确的 i
值了。希望对你有帮助!
英文:
Code:
arr := []string{"A", "B", "C", "D"}
i := 0
for i, s := range arr {
fmt.Println(i, s)
if s == "C" {
break
}
}
fmt.Println(i)
Output:
0 A
1 B
2 C
0
Expected:
0 A
1 B
2 C
2
I was expecting that I can access "i" outside for-range, since it was initialized beforehand. May be there is something related to scope of the variable that I am missing, if so how to achieve what I am expecting?
*Note: I am new to golang.
答案1
得分: 2
你在循环内部重新声明了变量 i
。请参考声明和作用域,特别是短变量声明。
只要你在外部作用域中声明它们,你可以在循环内部和外部都访问这些变量(https://go.dev/play/p/Q3OJ0mUZJH-)。
arr := []string{"A", "B", "C", "D"}
i := 0
s := ""
for i, s = range arr {
fmt.Println(i, s)
if s == "C" {
break
}
}
fmt.Println(i)
英文:
You are redeclaring your i
variable inside the loop. See Declarations and scope, specifically Short Variable Declarations.
You can access the variables both inside and outside of the loop, as long as you declare them both in the outer scope (https://go.dev/play/p/Q3OJ0mUZJH-)
arr := []string{"A", "B", "C", "D"}
i := 0
s := ""
for i, s = range arr {
fmt.Println(i, s)
if s == "C" {
break
}
}
fmt.Println(i)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论