Variable in for loop undefined outside

See the relevant section from the spec: Declarations and scope:

The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.

Define it in the scope in which you want to access it: before the for (in the scope of the main() function).

Also note that fmt.Sprintf() requires an additional parameter besides the ones to be printed: a format string. Either provide a format string (e.g. include a %s verb for the randomString parameter) or alternatively you may use fmt.Sprintln().

func main() {
    var randomString string
    for i := 0; i < 10000; i++ {
        randomString = fmt.Sprintf("a%sa\n", "test")
    }
    fmt.Println("Made 10000 random strings like", randomString)
}

Output:

Made 10000 random strings like atesta

Try it on the Go Playground.


This is scoping issue, in Go the scope of randomString is the loop body, in JS it would be the whole function. Scoping rules differ in the different languages.

Check the Go spec:

https://golang.org/ref/spec#Declarations_and_scope

Tags:

Scope

Go