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.
This does not even compile (I was answering the unedited version of the question).
You have to use ;
instead of ,
:
func main(){
a := 0
for i := 0; i < 10; i++ {
a += 5
}
fmt.Println(a) // prints 50
}