0
0
Goprogramming~20 mins

Switch expression behavior in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Go Switch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of switch with fallthrough
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")
        fallthrough
    case 3:
        fmt.Println("Three")
    default:
        fmt.Println("Default")
    }
}
ATwo\nThree
BTwo
CTwo\nDefault
DThree
Attempts:
2 left
๐Ÿ’ก Hint
Remember that fallthrough causes the next case to run even if it doesn't match.
โ“ Predict Output
intermediate
2:00remaining
Switch with multiple expressions
What will this Go program print?
Go
package main
import "fmt"
func main() {
    x := 5
    switch {
    case x < 0:
        fmt.Println("Negative")
    case x == 5:
        fmt.Println("Five")
    case x > 0:
        fmt.Println("Positive")
    default:
        fmt.Println("None")
    }
}
AFive
BPositive
CNegative
DNone
Attempts:
2 left
๐Ÿ’ก Hint
Switch without an expression evaluates cases as booleans in order.
โ“ Predict Output
advanced
2:00remaining
Switch with variable initialization and matching
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    switch x := 10; {
    case x < 5:
        fmt.Println("Less than 5")
    case x > 5:
        fmt.Println("Greater than 5")
    default:
        fmt.Println("Equal to 5")
    }
}
ALess than 5
BEqual to 5
CGreater than 5
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
The variable x is declared in the switch statement and used in case conditions.
โ“ Predict Output
advanced
2:00remaining
Switch with type assertion and interface
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)
    default:
        fmt.Println("unknown")
    }
}
ACompilation error
Bint 3
Cunknown
Dfloat64 3.14
Attempts:
2 left
๐Ÿ’ก Hint
Type switches check the dynamic type of an interface value.
โ“ Predict Output
expert
2:00remaining
Switch with multiple expressions and fallthrough
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    x := 1
    switch x {
    case 1, 2:
        fmt.Println("One or Two")
        fallthrough
    case 3:
        fmt.Println("Three")
    case 4:
        fmt.Println("Four")
    default:
        fmt.Println("Default")
    }
}
AOne or Two
BOne or Two\nThree
CThree
DOne or Two\nFour
Attempts:
2 left
๐Ÿ’ก Hint
fallthrough passes control to the next case regardless of matching.