Challenge - 5 Problems
Switch Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of a simple switch statement
What is the output of this Go program?
Go
package main import "fmt" func main() { x := 2 switch x { case 1: fmt.Println("One") case 2: fmt.Println("Two") case 3: fmt.Println("Three") default: fmt.Println("Other") } }
Attempts:
2 left
๐ก Hint
Look at the value of x and which case matches it.
โ Incorrect
The variable x is 2, so the switch matches case 2 and prints "Two".
โ Predict Output
intermediate2:00remaining
Switch with multiple cases and fallthrough
What will this Go program print?
Go
package main import "fmt" func main() { n := 1 switch n { case 1: fmt.Println("One") fallthrough case 2: fmt.Println("Two") case 3: fmt.Println("Three") default: fmt.Println("Default") } }
Attempts:
2 left
๐ก Hint
Remember that fallthrough makes the next case run too.
โ Incorrect
The switch matches case 1 and prints "One". The fallthrough causes case 2 to run next, printing "Two".
โ Predict Output
advanced2:00remaining
Switch with expression and no matching case
What is the output of this Go program?
Go
package main import "fmt" func main() { x := 10 switch { case x < 5: fmt.Println("Less than 5") case x > 20: fmt.Println("Greater than 20") default: fmt.Println("Between 5 and 20") } }
Attempts:
2 left
๐ก Hint
The switch has no expression, so it checks each case condition as a boolean.
โ Incorrect
x is 10, so x < 5 is false, x > 20 is false, so default runs printing "Between 5 and 20".
โ Predict Output
advanced2:00remaining
Switch with type assertion
What will this Go program print?
Go
package main import "fmt" func main() { var i interface{} = 3.14 switch v := i.(type) { case int: fmt.Println("int", v) case float64: fmt.Println("float64", v) case string: fmt.Println("string", v) default: fmt.Println("unknown") } }
Attempts:
2 left
๐ก Hint
The variable i holds a float64 value, so the type switch matches float64.
โ Incorrect
The type assertion switch matches float64 and prints "float64 3.14".
๐ง Conceptual
expert3:00remaining
Behavior of fallthrough in switch with multiple cases
Consider this Go code snippet:
var x = 2
switch x {
case 1, 2:
fmt.Println("One or Two")
fallthrough
case 3:
fmt.Println("Three")
case 4:
fmt.Println("Four")
}
What will be printed when this code runs?
Attempts:
2 left
๐ก Hint
fallthrough only moves to the next case, even if it has multiple values.
โ Incorrect
The switch matches case 1,2 and prints "One or Two". The fallthrough causes case 3 to run next, printing "Three". Case 4 does not run.