Control Flow

Switch Case in Go

A switch case is used test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed.


Syntax
//standard switch with variable, which can also have an assignment statement
switch variable {
    case valueOne:
        //do something
    case valueTwo:
        //do something
    default:
        //optional, occurs if above cases aren't reached
}

//switches can also be done without variables, this way they function similar to if/else
switch {
    case booleanExpression:
        //do something
}

Notes

The optional default case is for when the variable does not equal any of the cases.

Cases can be Boolean expressions. There can also be multiple cases on one line.

Like an if statement, a short statement can precede the case value.

Hitting a case will break the switch, unless the fallthrough statement is used.


Example
//assume fmt is imported, choice is a string
switch(choice) { 
    case 'Y' : 
        fmt.Println("Yes")
    case 'M' : 
        fmt.Println("Maybe")
    case 'N' : 
        fmt.Println("No")
    default: 
        fmt.Println("Invalid response")
}

< If Statement   |   For Loop >

© 2018 SyntaxDB. All Rights Reserved.