From the course: Go for Developers: Practical Techniques for Effective Coding
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Switch statements - Go Tutorial
From the course: Go for Developers: Practical Techniques for Effective Coding
Switch statements
- Switch Statements allow for the same type of logical decisions as if/else if statements, but tend to be easier to read and maintain. Consider this monstrous else if statement. It is full of redundant code and if an entry needs to be added in the middle of this statement, it could prove problematic. The switch statement is a more compact way to write the same logic. Here, we are able to replace the if/ else if statements with a switch statement and use the case keyword to evaluate each expression. Each expression is evaluated in order and the first one that evaluates the true is used. We can clean up the switch statement to remove the redundant code in the case expressions. Each case expression is checking the month variable against the number. The switch statement allows for us to use an expression on the initial line. We can use this to remove the repeated month++ check for each case statement. Each case statement can then be simplified to case N where N is the number to check. Now…