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.
CodePudding user response:
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)