Golang program that uses switch, multiple value cases


Switch statements in Golang provide an elegant and concise way to control the flow of execution based on the value of a variable. In addition to the basic switch statement, Golang also provides the ability to have multiple values in a case statement. In this article, we will explore how to write a Golang program that uses switch statements with multiple value cases.

Basic Switch Statement

Before we dive into the multiple value case statements, let's first review the basic syntax for a switch statement in Golang. 

Example

Here's an example −

package main

import "fmt"

func main() {
   fruit := "apple"

   switch fruit {
      case "apple":
         fmt.Println("This is an apple")
      case "banana":
         fmt.Println("This is a banana")
      case "orange":
         fmt.Println("This is an orange")
      default:
         fmt.Println("This is not a fruit")
   }
}

Output

This is an apple

In this example, we have defined a variable fruit and set its value to "apple". We then use the switch statement to check the value of fruit. If the value is "apple", we print "This is an apple" to the console. If the value is "banana", we print "This is a banana", and so on. If the value does not match any of the cases, we print "This is not a fruit" to the console.

Multiple Value Cases

Now, let's take a look at how we can use multiple value case statements in a switch statement. 

Example

Here's an example −

package main

import "fmt"

func main() {
   letter := "a"

   switch letter {
      case "a", "e", "i", "o", "u":
         fmt.Println("This is a vowel")
      case "y":
         fmt.Println("This can be a vowel or a consonant")
      default:
         fmt.Println("This is a consonant")
   }
}

Output

This is a vowel

In this example, we have defined a variable letter and set its value to "a". We then use the switch statement to check the value of letter. If the value is "a", "e", "i", "o", or "u", we print "This is a vowel" to the console. If the value is "y", we print "This can be a vowel or a consonant". If the value does not match any of the cases, we print "This is a consonant" to the console.

Note that we can have multiple values in a single case statement separated by commas.

Conclusion

Switch statements with multiple value cases are a powerful feature of the Golang programming language that allows for more concise and readable code. By using multiple values in a case statement, you can reduce the amount of repetitive code and make your code more maintainable. As you become more familiar with Golang, you will find that switch statements with multiple value cases can be an essential tool in your programming toolbox.

Updated on: 18-Apr-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements