Infinite 'for' loop in Go

Issue

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.

Solution

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

Answered By – Ry-

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.