0
0
Goprogramming~20 mins

Switch statement in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Switch Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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")
  }
}
ATwo
BThree
COne
DOther
Attempts:
2 left
๐Ÿ’ก Hint
Look at the value of x and which case matches it.
โ“ Predict Output
intermediate
2: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")
  }
}
A
One
Two
Three
BTwo
C
One
Two
DOne
Attempts:
2 left
๐Ÿ’ก Hint
Remember that fallthrough makes the next case run too.
โ“ Predict Output
advanced
2: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")
  }
}
ABetween 5 and 20
BGreater than 20
CLess than 5
DNo output
Attempts:
2 left
๐Ÿ’ก Hint
The switch has no expression, so it checks each case condition as a boolean.
โ“ Predict Output
advanced
2: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")
  }
}
Aint 3
Bfloat64 3.14
Cunknown
Dstring 3.14
Attempts:
2 left
๐Ÿ’ก Hint
The variable i holds a float64 value, so the type switch matches float64.
๐Ÿง  Conceptual
expert
3: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?
A
One or Two
Three
Four
BOne or Two
CThree
D
One or Two
Three
Attempts:
2 left
๐Ÿ’ก Hint
fallthrough only moves to the next case, even if it has multiple values.