官术网_书友最值得收藏!

  • Security with Go
  • John Daniel Leon
  • 241字
  • 2021-06-30 19:06:49

switch, case, fallthrough, and default

The switch statement allows you to branch execution based on the state of a variable. It is similar to the switch statement in C and other languages.

There is no fallthrough by default. This means once the end of a case is reached, the code exits the switch statement completely unless an explicit fallthrough command is provided. A default case can be provided if none of the cases are matched.

You can put a statement in front of the variable to be switched, such as the if statement. This creates a variable whose scope is limited to the switch statement.

This example demonstrates two switch statements. The first one uses hardcoded values and includes a default case. The second switch statement uses an alternate syntax that allows for a statement in the first line:

package main

import (
"fmt"
"math/rand"
)

func main() {
x := 42

switch x {
case 25:
fmt.Println("X is 25")
case 42:
fmt.Println("X is the magical 42")
// Fallthrough will continue to next case
fallthrough
case 100:
fmt.Println("X is 100")
case 1000:
fmt.Println("X is 1000")
default:
fmt.Println("X is something else.")
}

// Like the if statement a statement
// can be put in front of the switched variable
switch r := rand.Int(); r {
case r % 2:
fmt.Println("Random number r is even.")
default:
fmt.Println("Random number r is odd.")
}
// r is no longer available after the switch statement
}
主站蜘蛛池模板: 大洼县| 台中市| 安新县| 建德市| 临潭县| 景宁| 紫阳县| 平凉市| 博客| 尼木县| 得荣县| 中宁县| 富顺县| 阳西县| 古丈县| 抚松县| 青州市| 永和县| 滦平县| 开江县| 东阳市| 南和县| 沈丘县| 保德县| 昌邑市| 长汀县| 和硕县| 逊克县| 当阳市| 神农架林区| 金山区| 江津市| 文昌市| 西乌珠穆沁旗| 乐都县| 大化| 巨鹿县| 贵阳市| 大关县| 昭通市| 东台市|