Go Switch project code

Go Switch Statement, More Flow Control

 

We’ve learned about for loops, and if/else if/else, now it’s time to introduce another flow control statement, the Go Switch. Most programming languages have a version of the Switch statement and Go is no exception. The Go Switch statement is functionally very similar to a big if/else if/else statement but can make your code much more readable when you would have many “else if” blocks.

Go Switch Keyword

The Go Switch statement has two main parts. The first part is the “switch” keyword. The switch keyword is the often referred to as the “control expression.” The control expression can either be a variable or an expression that produces a value. We’ll use this value as part of a comparison expression in the second part of the Go Switch statement.

1
2
3
4
5
6
7
8
9
package main

func main () {
    animal := "dog"

    switch animal {

    }
}

We’ve created a string variable named “animal” with the value of “dog”. Then we’ve used the “animal” variable as the control statement for our Go Switch.

Go Switch Case

The Second part of our Go Switch statement is the “case” keyword. The case statement is like the conditional part of our if statement. Go will test each of our case statements in order starting at the top and working down until one evaluates to true. Once one of our case statements evaluates to true Go will stop evaluating the rest of the case statements in our Go Switch.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
    "fmt"
)

func main () {
    animal := "dog"

    fmt.Println("The", animal, "says ")

    switch animal {
    case "cat":
        fmt.Println("meow")
    case "dog":
        fmt.Println("woof")
    }
}

The Go Switch statement compares each case to the value of our control statement. If the values are equal, then the case is matched, and the code for that case is executed.

Go Switch Default Case

Just like how the if statement has the else keyword that tells Go what to do if none of your other if statements match there’s a default for the Go Switch statement as well. For the Switch statement, you use “default” to specify a case that should be executed if no other cases are matched.

1
2
3
4
5
6
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
    fmt.Println("It's the weekend!")
default:
    fmt.Println("It's a weekday")
}

The other thing to note in this code is that we created a case that will match for both Saturday and Sunday using the comma (,) to separate the values. We could have had two individual cases for the days, but then we would have written the same code twice to print out that it’s the weekend.

Go Switch Without Control Statement

We can also use the Go Switch statement without a control statement at all. When used this way the Switch acts exactly like an if statement. Each case must be an expression that evaluates to either true or false. If the expression evaluates to true then the case is matched.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
    "fmt"
    "time"
)

func main () {
    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Printf("It's %d:%dAM\n", t.Hour(), t.Minute())
    default:
        fmt.Printf("It's %d:%dPM\n", t.Hour()-12, t.Minute())
    }
}

In this code set a variable “t” to equal the current time using the “time” package. We have a case that checks if the hour of the time right now (based on a 24-hour clock) is less than 12. If the hour is not less than twelve, we know it must be more than 12, so we can just use a default case to handle that.

The other new thing to mention in our code is the Printf() function. Previously we’ve just been using the Println() function from the “fmt” package. Printf is like the Println function in that it prints our input to the screen. But instead of just printing it out on a new line it lets us specify the format of our output. The percent (%) “d” in our string tells Printf that we’re going to provide a number (digit) in that place of our string.

After the string argument to Printf, we pass in the actual values that we want the function to substitute for our format placeholders. The backslash (\) “n” in our format string tells Printf to print out a newline since unlike Println it doesn’t do that for us automatically.

Chris Sotherden

Originally a native of upstate NY, I relocated to North Carolina in 2013 where I've since helped open the new R&D headquarters for Optanix. I've been with Optanix (formerly ShoreGroup) for over ten years, where I've worked my way up from entry-level to Lead Architect. I taught myself programming in high school and am an all around technology nerd from the design of programming languages and compilers, to quantum computing, and rockets. Outside of technology I've competed in powerlifting and medium distance running, as well as smoking some mean BBQ. Oh, my partner and I also breed, show, and sell fancy goldfish!

>