dongtu0363 2017-08-01 18:31
浏览 39
已采纳

在帖子中调用函数的无限循环

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)
    }
}

compiler to play around

  • 写回答

2条回答 默认 最新

  • duanqiao2225 2017-08-01 18:34
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据