Learn Go: Golang Control Flow Statements: Switch #10

Golang provides Switch statement to evaluate an expression and run a case that matches

Gopher

Lets go!!

Published · Jan 15 2020

A Switch statement takes an expression and matches it against a list of possible cases. Once a match is found, it executes the block of code specified in the matched case.

Here is a simple example of switch statement -
package main import ( "fmt" ) func main() { finger := 4 switch finger { case 1: fmt.Println("Thumb") case 2: fmt.Println("Index") case 3: fmt.Println("Middle") case 4: fmt.Println("Ring") case 5: fmt.Println("Pinky") } }


Go evaluates all the switch cases one by one from top to bottom until a case succeeds. Once a case succeeds, it runs the block of code specified in that case and then stops (it doesn’t evaluate any further cases).

This is contrary to other languages like C, C++, and Java, where you explicitly need to insert a break statement after the body of every case to stop the evaluation of cases that follow.

If none of the cases succeed, then the default case is executed.
. . .

Default case

We have only 5 fingers in our hand. What will happen if we input a incorrect finger number. This is where the default case comes into picture. The default case will be executed when none of the other cases match.
package main import ( "fmt" ) func main() { switch finger := 8; finger { case 1: fmt.Println("Thumb") case 2: fmt.Println("Index") case 3: fmt.Println("Middle") case 4: fmt.Println("Ring") case 5: fmt.Println("Pinky") default: //default case fmt.Println("incorrect finger number") } }


In the above program finger is 8 and it does not match any of the cases and hence incorrect finger number is printed. It's not necessary that default should be the last case in a switch statement. It can be present anywhere in the switch.

You might also have noticed a small change in the declaration of finger. It is declared in the switch itself. A switch can include an optional statement which is executed before the expression is evaluated.

In this line switch finger := 8; finger finger is first declared and also used in the expression. The scope of finger in this case is limited to the switch block.
. . .

Switch with a short statement

Just like if, switch can also contain a short declaration statement preceding the conditional expression. So you could also write the previous switch example like this -
package main

import (
"fmt"
)

func main() {
switch dayOfWeek := 6; dayOfWeek {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
{
fmt.Println("Saturday")
fmt.Println("Weekend. Yaay!")
}
case 7:
{
fmt.Println("Sunday")
fmt.Println("Weekend. Yaay!")
}
default:
fmt.Println("Invalid day")
}
}


The only difference is that the variable declared by the short statement (dayOfWeek) is only available inside the switch block.
. . .

Multiple expressions in case

It is possible to include multiple expressions in a case by separating them with comma.
package main import ( "fmt" ) func main() { letter := "i" switch letter { case "a", "e", "i", "o", "u": //multiple expressions in case fmt.Println("vowel") default: fmt.Println("not a vowel") } }


The above program checks whether letter is a vowel of not. The line case "a", "e", "i", "o", "u": matches all the vowels. This program outputs vowel.
. . .

Expressionless switch

The expression in a switch is optional and it can be omitted. If the expression is omitted, the switch is considered to be switch true and each of the case expression is evaluated for truth and the corresponding block of code is executed.
package main import ( "fmt" ) func main() { num := 75 switch { // expression is omitted case num >= 0 && num <= 50: fmt.Println("num is greater than 0 and less than 50") case num >= 51 && num <= 100: fmt.Println("num is greater than 51 and less than 100") case num >= 101: fmt.Println("num is greater than 100") } }


In the above program the expression is absent in switch and hence it is considered as true and each of the case is evaluated. case num >= 51 && num <= 100: is true and the program outputs num is greater than 51 and less than 100.

This type of switch can be considered as an alternative to multiple if else clauses.

. . .

Type switch

A switch can also be used to discover the dynamic type of an interface variable. Such a type switch uses the syntax of a type assertion with the keyword type inside the parentheses.

If the switch declares a variable in the expression, the variable will have the corresponding type in each clause. It's also idiomatic to reuse the name in such cases, in effect declaring a new variable with the same name but a different type in each case.
package main

import (
"fmt"
)

func main() {
var t interface{}
t = 10
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
}
. . .

Combining multiple Switch cases

You can combine multiple switch cases into one like so -
package main import "fmt" func main() { switch dayOfWeek := 5; dayOfWeek { case 1, 2, 3, 4, 5: fmt.Println("Weekday") case 6, 7: fmt.Println("Weekend") default: fmt.Println("Invalid Day") } }

This comes handy when you need to run a common logic for multiple cases.
. . .

Conclusion

This brings us to an end of this tutorial. There is one more type of switch called type switch. We will look into this when we learn about interfaces. In the next article, You’ll learn how to define functions in Go. See you in the next post!
. . .

. . .

Ritesh swamy

Jun 21 2019

Write your response...

On a mission to build Next-Gen Community Platform for Developers