I don't quite understand why a
is not 2 at the end:
func main (){
z := 4
if true {
z := 2
fmt.Println(z)
}
fmt.Println(z) // prints 4
}
I don't quite understand why a
is not 2 at the end:
func main (){
z := 4
if true {
z := 2
fmt.Println(z)
}
fmt.Println(z) // prints 4
}
z
is getting shadowed. Change :=
to =
and it will work.
func main (){
z := 4
if true {
z = 2
fmt.Println(z)
}
fmt.Println(z) // prints 2
}
The if statement has its own scope, when you used :=
you declared a new variable and shadowed the old one.