Golang Tutorial: (10) switch statement

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Original: https://golangbot.com/switch/

This is the tenth chapter of this Golang series of tutorials.

switchis a conditional statement that matches the evaluation result of an expression with a list of possible values and executes the corresponding code based on the matching result. You can think of a switch statement as an alternative to writing multiple if-else clauses.

Example is the best way to explain the problem, let's write a simple program, enter the finger number, output the corresponding finger name:). For example 0 means thumb, 1 means index finger etc.

 PackageMainImport("FMT")funcMain () {finger: =4    SwitchFinger { Case1: FMT. Println ("Thumb") Case2: FMT. Println ("Index") Case3: FMT. Println ("Middle") Case4: FMT. Println ("Ring") Case5: FMT. Println ("Pinky")    }}

In the above program, the case statement evaluates and matches sequentially (top to bottom) until it finger finds the first finger match and case executes the code in it. The value here is finger 4, so print Ring .

Multiple with the same value case is not allowed. If you run the following program, the compilation will be an error: duplicate case 4 in switch .

 PackageMainImport("FMT")funcMain () {finger: =4    SwitchFinger { Case1: FMT. Println ("Thumb") Case2: FMT. Println ("Index") Case3: FMT. Println ("Middle") Case4: FMT. Println ("Ring") Case4://duplicate CaseFmt. Println ("another Ring") Case5: FMT. Println ("Pinky")    }}

Default case

We only have 5 fingers per hand, but what happens if we enter an incorrect finger number? We're going to use default a statement here. When there is no other case match, the default statement is executed.

 PackageMainImport("FMT")funcMain () {SwitchFinger: =8; Finger {//finger is declared in switch     Case1: FMT. Println ("Thumb") Case2: FMT. Println ("Index") Case3: FMT. Println ("Middle") Case4: FMT. Println ("Ring") Case5: FMT. Println ("Pinky")default://default CaseFmt. Println ("Incorrect finger number")    }}

In the above program, finger the value is 8, it does not match any case , so print incorrect finger number . The default statement does not have to be placed at the end of the switch statement, but can be placed switch anywhere in the statement.

You may have found another small change that will be finger declared in the switch statement. switchA statement can contain an optional statement that executes before an expression evaluates to a value. In switch finger := 8; finger this line, it finger is declared first, and then evaluated as an expression. This approach (the way the translator notes: Declaring a variable in a switch statement ) finger can only be accessed in a switch statement.

Case with multiple expressions

You can case include multiple expressions in one, with each expression separated by commas.

package mainimport (      "fmt")func main() {      "i"    switch letter {    case"a""e""i""o""u"//multiple expressions in case        fmt.Println("vowel")    default:        fmt.Println("not a vowel")    }}

The above program detects letter if it is a vowel. case "a", "e", "i", "o", "u":This line matches all the vowels. The output of the program is: vowel .

Switch without an expression

switchThe expression in is optional and can be omitted. If you omit an expression, it is equivalent switch true , in this case, to compare the evaluation result of each case expression and, if it is true equal, to execute the corresponding code.

 PackageMainImport("FMT")funcMain () {num: = the    Switch{//Expression is omitted     CaseNum >=0&& Num <= -: FMT. Println ("num is greater than 0 and less than") CaseNum >=Wuyi&& Num <= -: FMT. Println ("Num is greater than, and less than") CaseNum >=101: FMT. Println ("num is greater than")    }}

In the above program, switch there is no expression at the back so it is considered switch true and case compared with the evaluation result of each expression true . case num >= 51 && num <= 100:the result of the evaluation is true , therefore the program output: num is greater than 51 and less than 100 . This type of switch statement can override multiple if else clauses.

Fallthrough

The case statement exits immediately after executing one of the runs in Go switch . fallthroughstatement is used to indicate that the case Next statement executes sequentially after the current statement is executed case .

Let's write a program to understand fallthrough . The following program detects number if it is less than 50,100 or 200. For example, if we enter 75, the program will print 75 less than 100 and 200, which is fallthrough achieved through a statement.

 PackageMainImport("FMT")funcNumber ()int{num: = the*5         returnNumfuncMain () {SwitchNum: = number (); {//num is not a constant     CaseNum < -: FMT. Printf ("%d is lesser than 50\n", num)Fallthrough     CaseNum < -: FMT. Printf ("%d is lesser than 100\n", num)Fallthrough     CaseNum < $: FMT. Printf ("%d is lesser than", num)}}

switchThe case expressions in and are not necessarily constants, they can also be evaluated at run time. Initialize the return value of the function in the program above num number() . The program evaluates the switc expression in h First, and then case evaluates and matches the expression in each of the values in turn true . The result of the match case num < 100: is true that the program prints: 75 is lesser than 100 , then the program encounters the fallthrough statement, so it continues to case evaluate the expression in the next and matches with true, and the result is still true , so print: 75 is lesser than 200 . The final output is as follows:

75is100  75is200  

fallthroughMust be the case last statement in a statement block. If it appears in the middle of the statement block, the compiler will error: fallthrough statement out of place .

There is also a switch statement called type switch , we will introduce it when learning the interface.

switchThe description of the statement ends here. Thanks for reading.

Directory
Previous: Golang Tutorial: (ix) Looping statements
Filed under: Golang Tutorial: (11) Arrays and slices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.