Introduction

I realize I have a quite a bit of Go posts in a row, but I have been having a lot of fun with it! I commence with Kubernetes in the next post! Today, I am going to be talking about switch statements.

Switch Statements

The switch statement is similar to an if statement, but it has a different syntax. Go executes a switch statement from top to bottom. The first case condition that is true, will be executed.

Let’s say we have a condition expression like so:

city := "Phoenix"
switch city {
case "Seattle":
  fmt.Println("Washington")
case "Minneapolis":
  fmt.Println("Minnesota")
case "Phoenix":
  fmt.Println("Arizona")
default:
  fmt.Print("No matches!")
}

city is the condition expression. The switch’s condition determines the type of the case condition. For example, one of the case clauses is case “Seattle”:. The case condition expression is “Seattle”. You can think of this as an if statement: if city == “Seattle” { do something }. The condition expression is compared for each case condition. The default clause will be executed if no cases match. NOTE: you can add multiple conditions to each cast clause. For example, instead of saying case “Seattle”:, you could say case “Seattle”, “Olympia”, “Othello”:. If one of the cities matches, Washington will be printed.

Switch Statement vs If Statement

When should you use a switch statement instead of an if statement? A switch statement can make longer if statements more readable. Let’s take this example if statement and convert it to a switch statement:

package main
import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) !=2 {
		fmt.Println("Please enter a dog breed.")
		return
	}

	b := os.Args[1]

	if b == "Boxer" || b == "Doberman Pinscher" || b == "Alaskan Malumute" {
		fmt.Println("Your dog is part of the Working Group and they are intelligent and strong.")
	} else if b == "Collie" || b == "Old English Sheepdog" || b == "Australian Shepherd" {
		fmt.Println("Your dog is part of the Herding Group and can control the movement of other animals.")
	} else if b == "Bull Terrier" || b == "Border Terrier" || b == "Rat Terrier" {
		fmt.Println("Your dog is part of the Terrier Group and is feisty and energetic.")
	} else if b == "Chihuahua" || b == "Pug" || b == "Shih Tzu" {
		fmt.Println("Your dog is part of the Toy Group and is an affectionate and attentive companion.")
	} else {
		fmt.Printf("%q was not found. Try again.\n", b)

	}
}

Converted to a switch statement:

package main
import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) !=2 {
		fmt.Println("Please enter a dog breed.")
		return
	}

	switch b := os.Args[1]; b {
        case "Boxer", "Doberman Pinscher", "Alaskan Malumute":
		fmt.Println("Your dog is part of the Working Group and they are intelligent and strong.")
	case "Collie", "Old English Sheepdog", "Australian Shepherd":
		fmt.Println("Your dog is part of the Herding Group and can control the movement of other animals.")
	case "Bull Terrier", "Border Terrier", "Rat Terrier":
		fmt.Println("Your dog is part of the Terrier Group and is feisty and energetic.")
	case "Chihuahua", "Pug", "Shih Tzu":
		fmt.Println("Your dog is part of the Toy Group and is an affectionate and attentive companion.")
	default: 
		fmt.Printf("%q was not found. Try again.\n", b)
	}
}

If you run it a few times, you can test it out and see that it still works the same:

fritzie@underacloud ~/dog-breed $ 
fritzie@underacloud ~/dog-breed $ go run main.go "Boxer"
Your dog is part of the Working Group and they are intelligent and strong.
fritzie@underacloud ~/dog-breed $ go run main.go "Bull Terrier"
Your dog is part of the Terrier Group and is feisty and energetic.
fritzie@underacloud ~/dog-breed $ go run main.go "Pug"
Your dog is part of the Toy Group and is an affectionate and attentive companion.
fritzie@underacloud ~/dogbreed $ go run main.go 
Please enter a dog breed.
fritzie@underacloud ~/dog-breed $ go run main.go "Monster"
"Monster" was not found. Try again.

Conclusion

In this post, we learned about the switch statement and how it can be used to simplify long if statement. In my opinion, I think the switch statement is much easier to read in this particular case!

To learn about different switch statement patterns, check out the following link: https://yourbasic.org/golang/switch-statement/

This error message is only visible to WordPress admins

Error: No feed found.

Please go to the Instagram Feed settings page to create a feed.