golang

Golang Type Switch Examples

In Go, the type switch statement concisely examines the concrete type of interface value. Through this, we can compare the type of interface variable against different cases and execute the corresponding code block based on the matched type. The syntax of a type switch is similar to a regular switch statement. But instead of comparing the values, it compares the types. This article delves into the concept of type switches in Go with some practical examples.

Example 1: Golang Type Switch Usage

The switch statement is used with the defaults option which is useful for handling the unexpected or unsupported types.

package main
import (
    "fmt"
)
func f(s1 string) {
    switch s1 {
        case "grade1":
        fmt.Println("A")
        case "grade2":
        fmt.Println("B")
        case "grade3":
        fmt.Println("C")
        case "grade4":
        fmt.Println("Fail")
        default:
        fmt.Println("NIL")
    }
}
func main() {
    f("grade1")    
    f("grade1grade2grade3")
}

Here, we define the “f” function with a single parameter which is “s1” of a type “string”. This function takes a string as input and uses a switch statement to determine the corresponding grade based on the value of “s1”. Inside the switch statement, each case represents a different possible value of “s1”.

In case none of the case statements match the value of “s1”, the default case is executed, and it prints “NIL”. Then, we make two function calls to “f” with different inputs inside the main() function. There, the first call of f(“grade1”) passes the “grade1” string as the argument which matches the first case in the switch statement. Therefore, it prints “A”. After that, the second call of the f(“grade1grade2grade3”) function passes the “grade1grade2grade3” string which doesn’t match any case statements.

Hence, the output shows the execution of the first case and the default case:

Example 2: Golang Type Switch Optional Statement

Additionally, the switch statement in Go is also used with the optional initializer, separated from the expression by a semicolon (;).

package main
import (
    "fmt"
)
func main()
    switch int1 := 8; int1 % 2 == 0 {
    case true:
        fmt.Println("Even Integer")
    case false:
        fmt.Println("Odd Integer")
    }
}

Here, we define the program’s main() function where the switch statement is called. Inside the switch statement, we have the int1 % 2 == 0 expression as the condition. Before the switch keyword, we use the int1 := 8 assignment statement where int1 is assigned with the value of 8. The int1 % 2 == 0 expression checks whether “int1” is evenly divisible by 2, i.e., whether it is an even number. The true block case of code is executed by the code if the statement evaluates to true. Otherwise, if the expression evaluates to false, the code executes the false block case.

Thus, the output of the code displays the true block because the value of “int1” is 8 which is evenly divisible by 2:

Example 3: Golang Type Switch Matching Multiple Values

However, we can also use a type switch by listing multiple types in a single case statement.

package main
import "fmt"
func main() {
  WeekNames := "Sun"
  switch WeekNames {
    case "Sat", "Sun":
      fmt.Println("Weekend")
    case "Mon","Tues","Wed","Thurs","Fri":
      fmt.Println("Weekday")
    default:
      fmt.Println("Day not exists")
  }
}

Here, we declare and initialize a variable named “WeekNames” and assign it with the value of “Sun”. Then, depending on the case, the separate blocks of code are executed using the switch statement which is used to examine the specified conditions. Here, the “WeekNames” is the expression that is now being examined. The first case statement is the “Sat”, “Sun”: case which checks if the “WeekNames” is equal to either “Sat” or “Sun”. After that, we set the second case statement which is the “Mon”, “Tues”, “Wed”, “Thurs”, “Fri”: case which checks if the “WeekNames” is equal to any of the specified weekdays.

The results output the “Weekend” because the value of “WeekNames” is “Sun” which matches the first case in the switch statement:

Example 4: Golang Type Switch Using Fallthrough

Moreover, the fallthrough statement is also used in a type switch to execute the code block of the next matching case even if the condition for that case is not met.

package main
import (
    "fmt"
)
func main() {
    nextlight := "Green"
    fmt.Println("Traffic light ahead:")
    switch nextstop {
    case "Red":
        fmt.Println("Red")
        fallthrough
    case "Yellow":
        fmt.Println("Yellow")
        fallthrough
    case "Green":
        fmt.Println("Green")
    }
}

Here, we define and initialize a “next light” variable and assigne it with the “Green” value. Similar to all of the aforementioned instances, we use the switch expression to assess the different conditions and perform the various blocks of code in accordance with the corresponding case. The expression that is being assessed in this instance is the “next light”. Note that we use the “fallthrough” keyword after the first two cases to indicate that the execution should continue to the next case without checking its condition. In this case, it falls through to the next case statement which prints “Green” to the console.

The program is completed and the outputs show the following result:

Example 5: Golang Type Switch with a Break Statement

Furthermore, the switch type can also be achieved within the body of a “for” loop in Go just like in the following illustration to iterate over a collection and perform the different actions based on the type of each element.

package main
import (
    "fmt"
)
func main() {
    str := "Golang Tutorial"
    for index, char := range str {
        switch char {
        case 'a', 'A':
            if char == 'a' {
                fmt.Println("Lowercase a at position", index)
                break
            }
            fmt.Println("Uppercase A at position", index)
        case 'l':
            fmt.Println("l at position", index)
        }
    }
}

Here, we assign the “Golang Tutorial” value to the “str” variable which is the string that we iterate over. After that, the “for” loop iterates through every character in the “str” string. Additionally, the value and index of each character in the string are returned using the range. In each iteration, the index is stored in the “index” variable, and the character is stored in the “char” variable. Then, the switch statement performs the different actions based on the value of the char. Note that there is an additional check if char == “a” to differentiate between the lowercase “a” and uppercase “A” for the first case. In the end, the break statement exits the switch statement and continues with the next iteration of the “for” loop.

Therefore, the output reflects the matched cases and their respective positions in the string:

Example 6: Golang Type Switch without Expression

The type switch can also be used without an expression to match against the types of interface values. The switch without expression in Go is used in the following:

package main
import "fmt"
func main() {
  Days := 366
  switch {
    case 366 == Days:
      fmt.Println("It's Leap Year")      
    default:
      fmt.Println("Not Leap Year")
  }
}

Here, the “Days” variable is created with the value which represents the number of days in a leap year. Then, we use the switch statement without an expression. In this case, the switch evaluates the conditions that are specified in the individual cases to determine which case to execute. The condition checks if “366 == Days” is true or not.

The output represents that the given days are a leap year:

Conclusion

The type switch in Go is illustrated here in the article with various examples. Therefore, type switches in Go provide a powerful mechanism to handle the different types of variables at runtime.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content