Getting started with Go — Switch Statements

Matthew Boyd
1 min readDec 24, 2021

In Go, switch statements are for the most part very similar to a lot of other languages. Their general syntax is as follows:

switch condition {case answer:   //do somethingdefault:}

So for example, we could do the following:

switch time.Now().Day() {case 0:fmt.Println("Monday")case 1:fmt.Println("Tuesday")case 2:fmt.Println("Wednesday")case 3:fmt.Println("Thursday")case 4:fmt.Println("Friday")case 5, 6:fmt.Println("Weekend!!")}

Notice how there are no break statements, go will do this automatically for you at compilation stage, so there’s no need to include them.

There’s another keyword that we can use in switch statements, fallthrough , this will allow us for instance, to go to the first case, and it will continue to evaluate the next cases as well.

An example is below:

answer := 15switch {case answer%5 == 0:fmt.Println("It is divisible by 5")fallthroughcase answer%3 == 0:fmt.Println("It is divisible by 3")default:fmt.Println("The answer is neither divisible by 5 or 3")}

output:

It is divisible by 5
It is divisible by 3

--

--