在后置位置调用的无限循环函数。

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

Infinite loop with function call in post

问题

循环循环,当我通过函数递增i时,而不是通过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)
    }
}

编译器用于测试

英文:

Cycle loops, when I increment i by the function, but no via i++.

package main

import &quot;fmt&quot;

func increment(i int) (int) {
	i++
	return i
}

func condition_true(i int) (bool) {
	if i &lt; 10 {
		return true
	} else {
		return false
	}
}

func main() {
	for i := 1; condition_true(i); increment(i) {
		fmt.Println(i)
	}
}

compiler to play around

答案1

得分: 6

你应该这样做 i = increment(i)

否则,循环中使用的 i 不会被修改。

for i := 1; condition_true(i); i = increment(i) {
    fmt.Println(i)
}

这样的写法会按照你的预期工作。

https://play.golang.org/p/dwHbV1iY0_

或者,通过接收指向 i 的指针来允许 increment 修改 i

func increment(i *int) {
   *i++
}

然后在循环中这样使用

```go
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(&amp;i) {
	fmt.Println(i)
}

答案2

得分: 3

这是因为增量函数实际上并没有改变 i 的值,因为 i 是按值传递到函数中的。

只需在 for 循环中删除增量部分,并将其替换为 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++

huangapple
  • 本文由 发表于 2017年8月2日 02:31:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/45445263.html
匿名

发表评论

匿名网友

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

确定