Learn Switch case Golang tutorials & complete examples

This article covers the Switch case statements with expressions and types with various syntax examples in Golang.

Golang Switch case statements

Switch case executes a particular code block when we have multiple code blocks based on condition.

It is an alternative syntax to writing if-else block.

Unlike other programming languages like Java and C+, where, a break is needed to stop its execution. Go language stops its execution when the matching Case is executed. The Break keyword is not required.

There are two types of `Switch case statement types in the Go Programming language.

  • Expression Switch: In this case, Switch expressions are compared with case expressions.
  • Type Switch: Switch expression types compared with case expressions.

Golang Expression Switch case statement

Expression switch compares a Golang expression with a value of case expressions.

Here is a syntax for the switch case

switch (variable | boolean - expression | Integer type) {
    case boolean - expression | integer type
    The block of code contains statements
    case boolean - expression | integer type
    Block of code contains statements
    default: // default  case and it is optional
        Block of code contains statements
}

Following are the keynotes of expression switch.

  • Switch executes from top to bottom, Stop its execution when a matching case occurs.
  • It contains any number of case statements with each case statement containing an expression and a colon.
  • The default case is optional. It executes when the matching case is not executed. This placed the last case and a break is not required
  • Switch expression and case expression must be evaluated to the same type, Otherwise, it gives a compilation error.
  • For example, Switch evaluates to float and case evaluates to float only.
  • Curly braces for the case body is optional.
  • If there are many matched cases, the first matched cases are executed.

Golang Switch Case Example

Here is a basic example of switch-case statements.

In the below example, The number is declared with the value 1. In the switch, the number compares with the value of the number against all case statements. Case statements are evaluated from top to bottom.

Matched first executes its code block, In this case, 1 is matched, and 1 matched is displayed to the console. switch expression can be enclosed with parenthesis and without parenthesis i.e. both switch number or switch (number) are allowed and valid codes.

package main

import "fmt"

func main() {
    number: = 1
    switch number {
        case 1:
            fmt.Println("1 matched")
        case 2:
            fmt.Println("2 matched")
        case 3:
            fmt.Println("3 matched")
        case 4:
            fmt.Println("4 matched")
        default:
            fmt.Println("default matched")
    }
}

Output:

1 matched

If none of the case statements is matched, default fmt.Println statement is executed.

Following are various examples of the switch case.

The duplicate case with the same values are not allowed

In the below code, the duplicate case was declared with the same values - case 3 was declared two times.

The compiler gives compilation error - duplicate case 3 in switch previous case at

package main

import "fmt"

func main() {
    number: = 1
    switch number {
        case 1:
            fmt.Println("1 matched")
        case 2:
            fmt.Println("2 matched")
        case 3:
            fmt.Println("3 matched")
        case 3: // duplicate case is declared here - Compilation error
            fmt.Println("3 matched")
        case 4:
            fmt.Println("4 matched")
        default:
            fmt.Println("default matched")
    }
}

Default case executes when the matched case is not declared

What will happen when the number is given as 10? For the same example.

The matching case for the number is not defined in the code. Hence, the default case will be executed and printed default matched text will be printed to the console output.

package main

import "fmt"

func main() {
    number: = 11
    switch number {
        case 1:
            fmt.Println("1 matched")
        case 2:
            fmt.Println("2 matched")
        case 3:
            fmt.Println("3 matched")
        case 4:
            fmt.Println("4 matched")
        default:
            fmt.Println("default matched")
    }
}

output:

default matched

The default case is optional. It is advisable to be the last case statement, but there is no effect on the way of switch case functionality.

Switch with No expression or Condition in go language

The switch is declared without expression or condition.

When no expression is used, It treats switch case as a true value. Switch with no expression condition or value always equals switch true. Case expression always should be expression or condition.

package main

import "fmt"

func main() {
    number: = 11
    switch {
        case number > 10:
            fmt.Println("Number is greater than 10")
        case number > 20:
            fmt.Println("Number is greater than 20")
        case number > 30:
            fmt.Println("Number is greater than 30")
        default:
            fmt.Println("default matched")
    }
}

And the output of the program code is

the number is greater than 10

when no expressions in the switch case, the case expression must be non-constant

package main

import "fmt"

func main() {
    number: = 11
    switch {
        case 1:
            fmt.Println("1 matched")
        case 2:
            fmt.Println("2 matched")
        case 3:
            fmt.Println("3 matched")
        case 4:
            fmt.Println("4 matched")
        default:
            fmt.Println("default matched")
    }
}

The above code is not compiled. The reason is switch without expression code should have case non-constants.

The compilation error is invalid case 1 in a switch (mismatched types int and bool) Complete error for the command is go run filename

.\First.go:8:2: invalid case 1 in switch (mismatched types int and bool)
.\First.go:10:2: invalid case 2 in switch (mismatched types int and bool)
.\First.go:12:2: invalid case 3 in switch (mismatched types int and bool)
.\First.go:14:2: invalid case 4 in switch (mismatched types int and bool)

Switch case contains multiple expressions or conditions

It can have multiple expressions separated by a comma symbol.

Here is an example

package main
import "fmt"

func main() {
    weekday: = "tuesday"
    switch weekday {
        case "monday", "tuesday", "wednesday", "thursday", "friday":
            fmt.Println("Working Day")
        default:
            fmt.Println("Not working day: a weekend")
    }
}

The output of the above program is

Working Day

The above code, Code checks weekday is working day or not. The case is defined with multiple strings which are declared as working days.

fallthrough case in the switch statement in the case body

Normally, when the matched case is found with the switch case, the code inside the matched case executes, and the control exits from the switch case.

fallthrough case statement is a special functionality used to jump the control from the next immediate available case Fallthrough is a keyword in golang, hence it will not be used as a variable or function name.

package main

import "fmt"

func main() {
    number: = 1
    switch number {
        case 1:
            fmt.Println("1 matched")
            fallthrough
        case 2:
            fmt.Println("2 matched")
            fallthrough
        case 3:
            fmt.Println("3 matched")
        case 4:
            fmt.Println("4 matched")
        default:
            fmt.Println("default matched")
    }
}

The output of the above program is

1 matched
2 matched
3 matched

without the fallthrough case statement, The output is

1 matched

In the above code, Control comes to the matched case, case 1 is matched, a fallthrough statement exists, and Control transfers to the first line of code of the next case 2 statement. This statement is the last statement inside the code of the case statement.

If you declare fallthrough is not a line of code, It gives a compilation error. The following code gives fallthrough statement out of place

package main

import "fmt"

func main() {
    number: = 1
    switch number {
        case 1:
            fallthrough // not allowed as first or middle - compilation error
            fmt.Println("1 matched")
        case 2:
            fmt.Println("2 matched")
            fallthrough
        case 3:
            fmt.Println("3 matched")
        case 4:
            fmt.Println("4 matched")
        default:
            fmt.Println("default matched")
    }
}

Switch case floating values example

Switch and case expressions can also be declared with floating values, and it is valid code. Other languages are not supported to be used in switch case expressions.

Golang has no issues with it.

The below program contains floating numbers, and matched cases with floating values are evaluated. In this case, 6.5 matched is printed to the console.

func main() {
    number: = 6.5
    switch number {
        case 5.5:
            fmt.Println("5.5 matched")
        case 6.5:
            fmt.Println("6.5 matched")
        default:
            fmt.Println("default matched")
    }
}

And output of the above program is

6.5 matched

Switch case String literals in golang

The expression can also be string literals.

String literals are a group of characters enclosed in double quotes.

It checks the exact match of string literals.

In the below code, the Case contains String literals, the Switch expression contains string variable, the Matched case is evaluated, and the output is TWO matched

func main() {
 number := "TWO"
 switch number {
 case "ONE":
  fmt.Println("ONE matched")
 case "TWO":
  fmt.Println("TWO matched")
 default:
  fmt.Println("default matched")
 }
}

The output of the above program is

TWO matched

Break statement to exit from the loop

The break statement can also be used in switch cases.

It is used to exit from the inner loop inside the switch.

When you are using a for loop with a switch case, the break keyword will be used.

Here is an example without a break statement for loop iterates with 3 values, Inside the loop, Switch is declared, and matched cases values are printed.

func main() {
    var numbArray = [3] int {
        1, 2, 5
    }
    for _, numb: = range numbArray {
        switch numb {
            case 1:
                fmt.Println("1 matched")
            case 2:
                fmt.Println("2 matched")
                break
            case 0:
                fmt.Println("0 matched")
        }
    }
}

Output:

1 matched
2 matched

Now we will rewrite the code with break and named labels in switch-case statements.

In the below loop code, for the first matched case, the break label is used, It exists from the named label and outputs only 1 matched case.

func main() {
    var numbArray = [3] int {
        1, 2, 5
    }
    MyLoopName:
        for _, numb: = range numbArray {
            switch numb {
                case 1:
                    fmt.Println("1 matched")
                    break MyLoopName
                case 2:
                    fmt.Println("2 matched")
                    break
                case 0:
                    fmt.Println("0 matched")
            }
        }
}

Output:

1 matched

Functions can be used as Expression in switch and case

The expression can also be a function named calls and valid in go language.

Following is an example of functions in switch expressions.

In the below example, the Simple function is declared, It just returns the passed parameter no value is processed. This is being used in Switch expression as well as case expression.

func myfunction(parameter string) string {
    return parameter
}
func main() {
    switch myfunction("mon") {
        case myfunction("mon"), myfunction("tue"), myfunction("wed"), myfunction("thu"), myfunction("fri"):
            fmt.Println("working day")
        case myfunction("sat"), myfunction("sun"):
            fmt.Println("Not working day: weekend")
    }
}

Output:

working day

Type Switch in Goland

Type switch is mostly used in interfaces.

Type switch is the way of checking multiple types and evaluating the first matched type case. These are mostly used to type assertions Difference between the expression switch and type switch, is the Normal switch compared values with case values.

Type switch compares types not values with case types. Here is a syntax for type switch

func main() {
    switch variable. (type) {
        case type:
            Code block statements
        case type:
            code block statements
        default:
            code block statements
    }
}

variable.(type) represents type assertion that contains a specific type as “type”. Following are key points of the type switch expressions

  • You can define any number of case statements
  • The expression defined in this type always of the interface type variable
  • Like a normal switch expression, Default is also optional, and last declared, the break is not required.
  • Switch type and case type must be of the same type or follow the is-a principle.
  • When switch type and case type are matched, the matched case code body is executed, and exits from the switch code, Break is not required

switch type assertion interface example

In the below example, interface() is an empty interface type that can accept any type of value.

package main

import "fmt"

func main() {
    var interfaceDemo interface {} = 45

    switch interfaceDemo.(type) {
        case string:
            fmt.Println("string type matched")
        case int:
            fmt.Println("int type matched")
        default:
            fmt.Println("default type matched")

    }
}

The output:

int type matched

type switch struct example

Type switch caseccan be used withcstruct` data types.

The struct type contains a custom type that contains multiple types.

package main

import "fmt"

func main() {
    type Employee struct {
        ID int
        Name string
    }
    emp: = Employee {
        1, "Kiran"
    }
    var empInterface interface {}
    empInterface = emp
    switch empInterface.(type) {
        case Employee:
            fmt.Println("Employee type matched")
        case string:
            fmt.Println("String type matched")
        default:
            fmt.Println("default type matched")
    }
}

Output:

Employee type matched

Conclusion

Learn about the complete tutorial switch case examples in golang.