shadowing iteration variable inside for loop

48 Views Asked by At

I am new to the Go programming language and find a strange behaviour. Go allows me to redefine a variable of the same name as the iteration variable. I need an explanation. Thank you!

package main

import (
    "fmt"
)

func main() {
    run()
    fmt.Scanln()
}

func run() {
    for x := 1; x < 10; x++ {
        x := x // How is this possible?
        go func() {
            fmt.Println(x)
        }()
    }
}

0

There are 0 best solutions below