在使用for-range循环时,当调用break语句时,如何获取索引呢?

huangapple go评论85阅读模式
英文:

How get index when break was called, in a for-range loop?

问题

代码中的问题是变量 ifor 循环中重新声明并赋值,导致在循环结束后,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)

huangapple
  • 本文由 发表于 2021年12月16日 22:52:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/70381078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定