golang

Golang Switch Case

A switch case in programming refers to a selection control mechanism that allows you to execute specific instructions based on the different actions. Simply put, it is an easier and more efficient way of writing multiple if-else statements.

This guide will look at how we can use switch statements using the go programming language.

Go Switch Statement

A switch statement allows the program to decide the action to take based on the options selectively.

Before applying switch statements in go, let us look at an example of how to accomplish a similar task using an if…else statement.

Consider the example program below:

package main
import"fmt"
func main() {
    db := "MySQL"
    ifdb == "SQLite" {
        fmt.Println("Port: None")
    } elseifdb == "SQL Server" {
        fmt.Println("Port: 1433")
    } elseifdb == "MongoDB" {
        fmt.Println("Port: 27017")
    } elseifdb == "MySQL" {
        fmt.Println("Port: 3306")
    } else {
        fmt.Println("Database Not Supported!")
    }
}

In the example above, we create a variable called db to store a string containing the database. We then use an if statement to check if the value of the db variable is equal to “SQLite” if true, print the running port for the database server.

Notice that we implement many else-if statements to check for each potential outcome.

Although the above code works, it is not very readable and contains near-duplicate lines.

To clean and organize the code above, we can use a switch statement.

In go, we create a switch statement using the switch keyword, followed by the variable which to compare various outcomes.

We then create a case block that defines the action based on the outcome.

For example:

packagemain
import "fmt"
funcmain() {
    db:= "MySQL"
    switch db {
    case "SQLite":
        fmt.Println("port: None")
    case "SQL Server":
        fmt.Println("Port: 1433")
    case "MongoDB":
        fmt.Println("Port: 27017")
    case "MySQL":
        fmt.Println("Port: 3306")
    default:
        fmt.Println("Database Not Supported!")
    }
}

We start by calling the switch keyword, followed by the variable, to compare.

We then implement switch statements to check for matching cases. If a case evaluates to true, we execute that block.

We also add a default case which is used as an else statement. This executes if neither of the defined cases evaluates to true.

Case Check Multiple

You can have a case statement checking for more than one value. For example, consider the example code below

case "MySQL", "Apache":

fmt.Println("Port: 3306")

fmt.Println("Port: 80")

We check if the case is either “MySQL” or “Apache” in the example above. If true, we execute the code block inside the case statement.

Fallthrough

We can use the fallthrough keyword to transfer the control to the next case. If the compiler encounters the fallthrough keyword, it moves out of the current switch statement and goes to the next. For example:

switchdb {
    case"SQLite":
        fmt.Println("port: None")
        fallthrough
}

Here, the compiler will exit the first case when it encounters the fallthrough keyword.

Note: All the code that comes after the fallthrough keyword (inside the case block) will not run. Hence, ensure the switch statement is the last part of the case block.

Switch with Conditional Operators

We can use a switch statement with conditional operators. Consider the example below:

age := 22
switch {
case age <= 18&& age = 25&& age <= 35:
    fmt.Println("Price: $15")
case age = 45:
    fmt.Println("Price: $20")
default:
    fmt.Println("Out of age bound")
}

Note that we do not include the variable after the switch keyword. We create logical comparisons for each case block and execute the specific conditions if true.

Closing

This guide covered the basics of working with switch statements in go. Using a switch, you can create comparisons for specific cases and take action if an action is true.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list