Go by Example : Switch

The switch statement is a shorthand for multiple if-else statements in Go. It tests multiple values against a single value (the “switch value”) and executes the first case that matches the switch value.

Here’s an example:

package main

import "fmt"

func main() {
    switch "docker" {
    case "linux":
        fmt.Println("Linux is the best!")
    case "docker":
        fmt.Println("Docker is amazing!")
    default:
        fmt.Println("I love open source.")
    }
}

Output:

Docker is amazing!

Note that Go’s switch statement does not require a break statement after each case, as it automatically breaks after executing the matched case. However, if you want to execute multiple cases, you can use the fallthrough keyword to allow execution to continue to the next case.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *