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

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.

主站蜘蛛池模板: 和林格尔县| 隆昌县| 虞城县| 巴马| 景德镇市| 常山县| 张家港市| 昌乐县| 理塘县| 图片| 龙口市| 涪陵区| 类乌齐县| 民勤县| 都安| 遵义县| 南溪县| 南陵县| 屯昌县| 高平市| 黄骅市| 娄底市| 兴宁市| 宁远县| 新干县| 渑池县| 榆中县| 德阳市| 宁城县| 深水埗区| 博白县| 兖州市| 大英县| 前郭尔| 扬州市| 芜湖市| 长顺县| 宝丰县| 商丘市| 绥棱县| 保山市|