0
0
Goprogramming~20 mins

Short variable declaration in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Go Short Variable Declaration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
}
A5 10
B0 0
C10 5
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
Remember that := declares and initializes variables, and you can swap values using multiple assignment.
โ“ Predict Output
intermediate
2: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)
    }
}
ANo output
B0
CCompilation error
D7
Attempts:
2 left
๐Ÿ’ก Hint
The variable x is declared and initialized in the if statement condition.
โ“ Predict Output
advanced
2: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)
}
A10 30
B20 30
CCompilation error
D10 0
Attempts:
2 left
๐Ÿ’ก Hint
Short variable declaration can redeclare variables if at least one new variable is declared.
โ“ Predict Output
advanced
2: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)
}
A5
B10
C0
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
The blank identifier _ ignores the second value.
๐Ÿง  Conceptual
expert
3: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)
        }
    }
}
A3
B2
C1
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
Each nested block can declare a new variable with the same name, shadowing outer ones.