- Hands-On Full Stack Development with Go
- Mina Andrawos
- 205字
- 2021-07-02 12:33:32
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.
推薦閱讀
- HTML5+CSS3+JavaScript從入門到精通:上冊(微課精編版·第2版)
- C++程序設計(第3版)
- Apache Oozie Essentials
- Python應用輕松入門
- Web全棧工程師的自我修養
- 用Python實現深度學習框架
- Linux命令行與shell腳本編程大全(第4版)
- Frank Kane's Taming Big Data with Apache Spark and Python
- HTML+CSS+JavaScript網頁設計從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- OpenStack Networking Essentials
- Visual Basic 程序設計實踐教程
- 寫給青少年的人工智能(Python版·微課視頻版)
- Spring Boot從入門到實戰
- INSTANT Lift Web Applications How-to
- Perl 6 Deep Dive