The following code is expected to fail with an error on compilation:
package main
import (
"fmt"
)
func main() {
x := 10
x := x + 1
fmt.Println(x)
}
The compilation error is:
./prog.go:9:4: no new variables on left side of :=
So I was expecting this code to also fail with error:
package main
import (
"fmt"
)
func main() {
if x := 10; x < 10 {
fmt.Println("if block: x:", x)
} else if x := x + 1; x < 20 {
fmt.Println("else if block: x: ", x)
}
}
Here is the output:
else if block: x: 11
Why does the second program succeed even though the := operator in else if x := x + 1 is not defining any new variable?
