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.

//standard switch with variable, which can also have an assignment statement
switch variable {
    case valueOne:
        //do something
    case valueTwo:
        //do something
        //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


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.

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

< If Statement   |   For Loop >

© 2019 SyntaxDB. All Rights Reserved.