douqi5079 2017-08-12 08:00
浏览 891
已采纳

Golang中的无限for循环[重复]

This question already has an answer here:

I'm new to Golang, but I would expect not to have issues with something as basic as this.

package main

import "fmt"

func main() {
    s := make([]int, 0)
    s = append(s, 1)
    for len(s) != 0 {
        j := len(s) - 1
        top, s := s[j], s[:j]
        fmt.Printf("top = %+v
", top)
        fmt.Printf("s = %+v
", s)
        fmt.Printf("len(s) = %+v
", len(s))
    }
}

This command doesn't exit, it just prints

len(s) = 0
top = 1
s = []
len(s) = 0
top = 1
s = []
len(s) = ^C

I find this stunning; what am I doing wrong? Syntactically, based on https://tour.golang.org/flowcontrol/3, everything seems OK.

</div>
  • 写回答

1条回答 默认 最新

  • drouie2014 2017-08-12 08:03
    关注

    When you use :=, you declare new variables. An s is created inside the loop unrelated to the s outside it. Assign instead:

    for len(s) != 0 {
        j := len(s) - 1
        var top int
        top, s = s[j], s[:j]
        fmt.Printf("top = %+v
    ", top)
        fmt.Printf("s = %+v
    ", s)
        fmt.Printf("len(s) = %+v
    ", len(s))
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示