Reputation: 35
I don't have any idea.
package main
import "fmt"
func main() {
mySlc := []int{1, 2}
count := 0
num := 5
fmt.Println(len(mySlc))
fmt.Print("Enter Len:")
for i := 0; i <= num-len(mySlc); i++ {
count++
var eded int
fmt.Print("Enter i:")
fmt.Scan(&eded)
mySlc = append(mySlc, eded)
}
fmt.Println(mySlc, count)
}
I don't have any idea. Why does this golang code return 2 times instead of 5?
Upvotes: 0
Views: 86
Reputation: 74
Well, that's right.
Upvotes: 2
Reputation: 496
mySlc
is being mutated during each loop iteration, and note that the i <= num - len(mySlc)
is being evaluated on each loop run. You can view this interactively by converting this to a while-loop with
for {
...
}
and inspecting the state of num - len(mySlc)
at each iteration.
Upvotes: 2