Golang Program that uses String Switch


Golang is a popular programming language that offers a range of powerful features. One of these features is the ability to use the switch statement with a string type variable. In this article, we will explore how to write a Golang program that uses a string switch statement.

What is a String Switch?

In Golang, the switch statement can be used to test a variable against a list of values. A string switch statement is a type of switch statement that is specifically designed to work with string variables.

A string switch statement works by comparing the value of a string variable against a list of possible values. If the value of the string variable matches one of the possible values, the corresponding case statement is executed.

Example

Let's take a look at an example Golang program that uses a string switch statement.

package main

import "fmt"

func main() {
   fruit := "banana"

   switch fruit {
      case "apple":
         fmt.Println("Selected fruit is apple.")
      case "banana":
         fmt.Println("Selected fruit is banana.")
      case "orange":
         fmt.Println("Selected fruit is orange.")
      default:
         fmt.Println("Unknown fruit selected.")
   }
}

Output

Selected fruit is banana.

In this example, we have defined a string variable named fruit and assigned it the value "banana". We then use the switch statement to compare the value of fruit against three possible values: "apple", "banana", and "orange".

If the value of fruit matches the first case statement, "Selected fruit is apple." is printed to the console. If the value of fruit matches the second case statement, "Selected fruit is banana." is printed. If the value of fruit matches the third case statement, "Selected fruit is orange." is printed.

If the value of fruit does not match any of the case statements, the default statement is executed, which prints "Unknown fruit selected." to the console.

Conclusion

String switch statements are a powerful feature of the Golang programming language. They allow you to easily compare the value of a string variable against a list of possible values and execute code based on the result. By using string switch statements in your Golang programs, you can write code that is more efficient, more readable, and more maintainable.

Updated on: 18-Apr-2023

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements