3

I'm new to Go, 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\n", top)
        fmt.Printf("s = %+v\n", s)
        fmt.Printf("len(s) = %+v\n", 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yangmillstheory
  • 1,055
  • 13
  • 31
  • Going off question , if you ever want to break infinite loop one way is using "os.exit(0)" . May it help users who are new to Golang. – infiniteLearner Jun 30 '20 at 09:44

1 Answers1

6

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\n", top)
    fmt.Printf("s = %+v\n", s)
    fmt.Printf("len(s) = %+v\n", len(s))
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • (at the time of this writing, this is [1/3 of my answers about Go](https://stackoverflow.com/questions/45137897/use-of-variable-in-for-loop-not-recognized-in-golang/45138077#45138077)) – Ry- Aug 12 '17 at 08:04
  • 1
    @YvetteColomb: I knew it was a duplicate but wanted to give an explanation with a more complete code example. – Ry- Aug 12 '17 at 08:06
  • I was under the impression that `:=` was smart enough to not redeclare variables already in scope in the case of a tuple where one entry is already in scope. Apparently I was wrong. – yangmillstheory Aug 12 '17 at 08:12