Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
switch
golang
communitycreator

How to perform a switch statement in Go

Chinweuba Elijah Azubuike

Overview

Knowing how to use a switch statement is one of the fundamentals of programming because it always comes in handy, instead of using a long continuous if else statement.

What is a switch statement?

Like the word switch, the switch statement checks for matching variables or expressions to carry out an operation or function when those expressions or variables are matched. Switch statements are flow controls in a program.

Syntax

switch variable:= 1; {
	case "darwin"://
	fmt.Println("OS X.")// action to take
}
	

Code

Let’s jump right into the code:

package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Print("Go runs on ")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

Explanation

In the example given above, we use a switch statement to check the OS Edpresso uses for the GO platform.

  1. We import the necessary packages.
import (
	"fmt"
	"runtime"
)

The runtime package is used for the checking the Operating System (OS).

  1. runtime.GOOS gets the OS we are using. To verify the OS we are using, we pass it into a switch statement that checks each case.

  2. If the current OS matches the case, it will run whatever code is there.

For this instance, we just print to the screen.

RELATED TAGS

go
switch
golang
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring