GoLang - Switch

3 minute read

In this tutorial, you will learn about Switch in Go Programming with the help of example.

In Go programming, the 'switch' statement is a powerful control structure that allows you to choose from multiple alternatives based on the value of an expression. It provides an elegant and concise way to handle multiple cases and control program flow. In this tutorial, we will explore the basics of the 'switch' statement in Go programming, with examples and explanations in simple and easy-to-understand language. So let’s dive in and learn about 'switch' in Go!

Syntax:

The general syntax of the 'switch' statement in Go is as follows:

switch expression {
case value1:
    // code to execute if expression equals value1
case value2:
    // code to execute if expression equals value2
...
default:
    // code to execute if none of the cases match
}

Simple Switch Statement

The simplest form of the 'switch' statement matches the value of an expression with predefined cases and executes the corresponding block of code.

Example:

package main

import "fmt"

func main() {
    var dayOfWeek = 3

    switch dayOfWeek {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    case 4:
        fmt.Println("Thursday")
    case 5:
        fmt.Println("Friday")
    case 6:
        fmt.Println("Saturday")
    case 7:
        fmt.Println("Sunday")
    default:
        fmt.Println("Invalid day")
    }
}

In the example above, we have a variable 'dayOfWeek' with a value of 3. The 'switch' statement evaluates the value of 'dayOfWeek' and executes the corresponding case. In this case, it matches the value 3 with the case '3' and prints “Wednesday” as the output.

Fallthrough

By default, Go’s 'switch' statement does not fall through to subsequent cases. However, you can explicitly specify fallthrough to execute the code of the next case.

Example:

package main

import "fmt"

func main() {
    var grade = "B"

    switch grade {
    case "A":
        fmt.Println("Excellent!")
    case "B":
        fmt.Println("Good!")
        fallthrough
    case "C":
        fmt.Println("Passable!")
    default:
        fmt.Println("Failed!")
    }
}

In this example, we have a variable 'grade' with a value of “B”. The 'switch' statement matches the value of 'grade' with the case "B" and prints “Good!”. However, by using the 'fallthrough' keyword after the “B” case, it falls through to the next case, which is "C". As a result, it also prints “Passable!” in addition to “Good!”.

Expressionless Switch

In Go, you can use the 'switch' statement without an expression, which allows you to create more complex conditions and evaluate different cases.

Example:

package main

import "fmt"

func main() {
    var num = 10

    switch {
    case num < 0:
        fmt.Println("Negative number")
    case num == 0:
        fmt.Println("Zero")
    case num > 0:
        fmt.Println("Positive number")
    }
}

In this example, we don’t have an expression after the 'switch' keyword. Instead, each case contains a condition that evaluates to true or false. The 'switch' statement checks each case condition and executes the block of code associated with the first true condition. Here, it evaluates the value of the variable 'num' and prints Positive number since 'num' is greater than 0.

package main

import "fmt"

func getType(i interface{}) {
    switch i.(type) {
    case int:
        fmt.Println("Integer")
    case float64:
        fmt.Println("Float")
    case string:
        fmt.Println("String")
    default:
        fmt.Println("Unknown type")
    }
}

func main() {
    getType(10)
    getType(3.14)
    getType("Hello")
    getType(true)
}

In this example, we define a function 'getType' that takes an empty interface 'i'. Inside the function, we use a type switch to determine the type of the value passed to 'i' and perform specific actions based on the type. It prints the corresponding message for each type, such as “Integer,” “Float,” “String,” or “Unknown type.”

Remember to pay attention to the syntax of the 'switch' statement and use appropriate cases and a default case to handle all possible scenarios. Experiment with different types of expressions and cases to familiarize yourself with the versatility of the 'switch' statement.

Conclusion

The 'switch' statement in Go programming provides a powerful way to handle multiple cases and make decisions based on the value of an expression. In this tutorial, we explored the basics of the 'switch' statement in Go, including simple switch statements, fallthrough, expressionless switch, and type switches. With these concepts, you can create more flexible and dynamic programs that adapt to different scenarios!

Congratulations on completing this beginner’s guide to the 'switch' statement in Go programming! Armed with this knowledge, you’re now equipped to handle multiple cases and make decisions based on the value of an expression. So go ahead, practice using the 'switch' statement in your Go programs, and unlock the full potential of decision-making in your code!

Updated: