Challenge - 5 Problems
Go Short Variable Declaration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of short variable declaration with multiple variables
What is the output of this Go program?
Go
package main import "fmt" func main() { a, b := 5, 10 a, b = b, a fmt.Println(a, b) }
Attempts:
2 left
๐ก Hint
Remember that := declares and initializes variables, and you can swap values using multiple assignment.
โ Incorrect
The variables a and b are declared and initialized with 5 and 10. Then their values are swapped using a, b = b, a. So the output is 10 5.
โ Predict Output
intermediate2:00remaining
Short variable declaration inside if statement
What will this Go program print?
Go
package main import "fmt" func main() { if x := 7; x > 5 { fmt.Println(x) } else { fmt.Println(0) } }
Attempts:
2 left
๐ก Hint
The variable x is declared and initialized in the if statement condition.
โ Incorrect
The short variable declaration x := 7 happens inside the if statement. Since 7 > 5 is true, it prints 7.
โ Predict Output
advanced2:00remaining
Short variable declaration with redeclaration and assignment
What is the output of this Go program?
Go
package main import "fmt" func main() { x := 10 x, y := 20, 30 fmt.Println(x, y) }
Attempts:
2 left
๐ก Hint
Short variable declaration can redeclare variables if at least one new variable is declared.
โ Incorrect
The first line declares x=10. The second line redeclares x and declares y. x is updated to 20, y is 30. So output is 20 30.
โ Predict Output
advanced2:00remaining
Short variable declaration with blank identifier
What will this Go program print?
Go
package main import "fmt" func main() { x, _ := 5, 10 fmt.Println(x) }
Attempts:
2 left
๐ก Hint
The blank identifier _ ignores the second value.
โ Incorrect
The variable x is assigned 5, the second value 10 is discarded using _. So printing x outputs 5.
๐ง Conceptual
expert3:00remaining
Short variable declaration behavior in nested scopes
Consider this Go code snippet. What is the value of x printed by the program?
Go
package main import "fmt" func main() { x := 1 { x := 2 { x := 3 fmt.Println(x) } } }
Attempts:
2 left
๐ก Hint
Each nested block can declare a new variable with the same name, shadowing outer ones.
โ Incorrect
Each block declares a new x. The innermost x is 3, so fmt.Println prints 3.