Cycle loops, when I increment i
by the function, but no via i++
.
package main
import "fmt"
func increment(i int) (int) {
i++
return i
}
func condition_true(i int) (bool) {
if i < 10 {
return true
} else {
return false
}
}
func main() {
for i := 1; condition_true(i); increment(i) {
fmt.Println(i)
}
}
You should do i = increment(i)
.
Otherwise, the i
used in the loop is not modified.
for i := 1; condition_true(i); i = increment(i) {
fmt.Println(i)
}
That one works as you'd expect.
https://play.golang.org/p/dwHbV1iY0_
Alternatively, allow increment
to modify i
by receiving a pointer to it:
func increment(i *int) {
*i++
}
And then use it like this in the loop:
for i := 1; condition_true(i); increment(&i) {
fmt.Println(i)
}
This is happening because the increment function isn't actually changing the i value because the i is passed by value into the function.
Simply remove the increment in the for loop and replace it with i++