DEV Community

Cover image for golang switch
tcs224
tcs224

Posted on

golang switch

If you want to evaluate cases in the Go programming language, you can use the switch statement. Like normal program execution, a switch statement is evaluated from top to bottom.

Instead of having a long list of if statements, a switch statement provides much cleaner code.

Switch example

The program below demonstrates the use of a switch statement. The switch statement exists in some other languages like C.

package main

import (
    "fmt"
)

func main() {
        x := 3

        switch x {
            case 0:
                fmt.Println("zero")
            case 1:
                fmt.Println("one")
            case 2:
                fmt.Println("two")             
            case 3:
                fmt.Println("tres")
        }
}

This outputs 'tres' because x is equal to 3. Instead of having a bulk of if statements you can use this.

The above program may not make sense, because we use a predefined condition. What if you you get it with keyboard input?

But instead of normal keyboard input, you need integer input. You can scan an integer like this:

fmt.Print("Enter x: ")
in := bufio.NewScanner(os.Stdin)
in.Scan()
x,_ := strconv.Atoi(in.Text())

So the switch statement with keyboard input gives:

package main

import (
    "fmt"
    "bufio"
    "os"
    "strconv"
)

func main() {
        fmt.Print("Enter x: ")
        in := bufio.NewScanner(os.Stdin)
        in.Scan()
        x,_ := strconv.Atoi(in.Text())

        switch x {
            case 0:
                fmt.Println("zero")
            case 1:
                fmt.Println("one")
            case 2:
                fmt.Println("two")             
            case 3:
                fmt.Println("tres")
        }
}

Top comments (0)