Gaaker Go

Golang switch statement

switch statement has below format´╝Ü

switch variable {
    case Possible-value1:
        // do something
    case Possible-value2:
        // do something
        // do something

There is a variable after the switch keyword, and the possible values of the variable after the case keyword. The optional default branch is usually placed at the end. It is equivalent to the last else branch of an if-else statement.

The case statements are tested one by one from top to bottom until the match is successful.

Once a branch is matched successfully, the entire switch code block will exit after executing the corresponding code, which means you don’t need to use a break statement to indicate the end.

The following is a complete code example.

package main

import "fmt"

func main() {
    animal := "sheep";
    switch animal {
    case "tiger":
        fmt.Println("I eat meat")
    case "deer", "sheep":
        fmt.Println("I eat grass")
        fmt.Println("No matching animals")

Below is the program output:

I eat grass
< switch statement switch statement >