In Go, you cannot directly add multiple conditions to a single case in a switch statement using logical operators (like ||). However, you can achieve this by combining conditions or writing a case block that evaluates an expression.

Here are two common approaches:


1. Use a single case with a conditional expression

Use a switch without a value and evaluate conditions in the case expressions.

go
package main

import "fmt"

func main() {
value := 10

switch {
case value == 10 || value == 20:
fmt.Println("Value is either 10 or 20")
case value == 30:
fmt.Println("Value is 30")
default:
fmt.Println("Value is something else")
}
}

  • Explanation:
    • The switch statement here does not specify a value to evaluate.
    • Each case can contain a boolean expression.

2. Group multiple case statements

You can group multiple cases to execute the same code block.

go
package main

import "fmt"

func main() {
value := 10

switch value {
case 10, 20:
fmt.Println("Value is either 10 or 20")
case 30:
fmt.Println("Value is 30")
default:
fmt.Println("Value is something else")
}
}

  • Explanation:
    • You can use a comma-separated list of values in a single case.
    • This is syntactic sugar for combining multiple conditions in one line.

Which Approach to Use?

  • Use Approach 1 (boolean expressions) when conditions are complex and involve comparisons or logical operators.
  • Use Approach 2 (comma-separated cases) when comparing against fixed values or constants.

Sign In

Sign Up