Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
x := 1
if true {
x := 2
fmt.Print(x, " ")
}
fmt.Println(x)
}2 1
- Expecting
2 2:x := 2inside theifdeclares a newxthat hides the outer one; the outerxstays1and is printed after the block. - Expecting a compile error for declaring
xtwice::=in an inner block declares a separate variable, which Go allows.
- How would you change one line so that the program prints
2 2? - Why does
x := 3right afterx := 1in the same block not compile?