azizovrafael
azizovrafael

Reputation: 35

Why does this golang code return 2 times instead of 5?

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

Answers (2)

Alexandr Kamenev
Alexandr Kamenev

Reputation: 74

Well, that's right.

  • The first iteration of the loop. i=0, 0 <= 5-2, Ok. An element is added.
  • The second iteration. i=1, 1 <= 5-3, Ok. An element is added.
  • The third iteration. i=2, 2 <= 5-4, No Ok. The cycle ends.

Upvotes: 2

akshayc
akshayc

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

Related Questions