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

The switch statement

Now, let's look at the switch statement. Here is what it looks like:

switch x {
case 5:
fmt.Println("5")
case 6:
fmt.Println("6")

default:

fmt.Println("default case")
}

If you haven't noticed already, there is no break keyword. In Go, each case breaks automatically, and doesn't need to be told to do so.

Similar to if statements, you can do an initialization in your switch statement:

switch x := getX();x {
case 5:
fmt.Println("5")
case 6:
fmt.Println("6")

default:

fmt.Println("default case")
}

In Go, a switch statement can act like a group of if else. This gives you the ability to write long if else chains with much nicer code:

switch{
case x == 5:
//do something
case x > 10:
// do something else
default:
//default case
}

In some scenarios, you want your switch cases not to break automatically, and instead fall through to the next case. For this, you can use the fallthrough keyword:

switch{
case x > 5:
//do something
fallthrough
case x > 10:
// do something else. If x is greater than 10, then the first case will execute first, then this case will follow
default:
//default case
}

Following conditional statements, let's take a look at loops.

主站蜘蛛池模板: 息烽县| 宁乡县| 西林县| 广饶县| 冕宁县| 搜索| 溧阳市| 南靖县| 金秀| 东港市| 当涂县| 宜春市| 义乌市| 新安县| 大丰市| 益阳市| 东至县| 乃东县| 沅江市| 岱山县| 平顺县| 潼关县| 璧山县| 连云港市| 托克逊县| 金阳县| 玉环县| 安宁市| 钟祥市| 玛纳斯县| 周口市| 弥勒县| 毕节市| 尖扎县| 青岛市| 邯郸市| 合川市| 满城县| 新干县| 北碚区| 基隆市|