Go Series Tutorial--10. Switch statement

Source: Internet
Author: User
Tags case statement
This is a creation in Article, where the information may have evolved or changed. This is the 10th article in the [Golang Series Tutorial] (/SUBJECT/2). Switch is a conditional statement that compares the value of an expression to a list of options that might match, and executes the corresponding block of code based on the matching situation. It can be thought of as a common way to replace multiple ' if Else ' clauses. Looking at code is easier to understand than text. Let's start with a simple example that takes the number of a finger as input and then prints the name of the finger. For example 0 is the thumb, 1 is the index finger and so on. "' Gopackage mainimport (" FMT ") func main () {finger: = 4 switch Finger {case 1:fmt. Println ("Thumb") case 2:fmt. Println ("Index") case 3:fmt. Println ("Middle") case 4:fmt. Println ("Ring") case 5:fmt. Println ("Pinky")}} "[Online Run Program] (https://play.golang.org/p/q4kjm2kpVe) in the above program, ' Switch finger ' will ' finger ' the value with each ' case ' Statement for comparison. Compares each value from top to bottom and executes the first logic that matches the value of the option. In the above example, the ' finger ' value is 4, so the result of printing is ' Ring '. In the list of options, ' case ' does not allow duplicates. If you try to run the following program, the compiler will report such an error: ' Main.go:18:2: In Tmp/sandbox887814166/main.go:16:7 ' ' Gopackage mainimport ("FMT") Func main () {finger: = 4 switch Finger {case 1:fmt. Println ("Thumb") case 2:fmt. Println ("Index") case 3:fmt. Println ("Middle") case 4:fmt. Println ("Ring") case 4://duplicates the FMT. Println ("another Ring") Case 5:fmt. Println ("Pinky")}} "[Running Program Online] (Https://play.Golang.org/p/sfxdchwdon) # # defaults (default case) Each of us has only 5 fingers in one hand. What happens if we enter an incorrect finger number? This should be the default situation. When other conditions do not match, the default is run. "' Gopackage mainimport (" FMT ") func main () {switch finger: = 8; finger {case 1:fmt. Println ("Thumb") case 2:fmt. Println ("Index") case 3:fmt. Println ("Middle") case 4:fmt. Println ("Ring") case 5:fmt. Println ("Pinky") Default://FMT. Println ("Incorrect finger Number")}} "[Running Program Online] (HTTPS://PLAY.GOLANG.ORG/P/FQ7U7SKHE1) The value of ' finger ' in the above program is 8, it does not conform to any of these circumstances, so it will print ' incorrect finger number '. Default does not have to appear only at the end of the switch statement, it can be placed anywhere in the switch statement. You may also notice that we have slightly changed the way the ' finger ' variable is declared. ' Finger ' is declared within the switch statement. Before the expression is evaluated, switch can choose to execute a statement first. In this line ' switch finger:= 8; Finger ', the ' finger ' variable is declared before it is used in the expression. Here, the scope of the ' finger ' variable is limited to this switch. # # Multiple expressions are judged by commas, you can include multiple expressions in a case. ' Gopackage mainimport ("FMT") func main () {letter: = "I" Switch letter {case "a", "E", "I", "O", "U"://One option multiple expressions Fmt . Println ("vowel") default:fmt. Println ("Not a Vowel")}} "[Running Program online] (Https://play.golang.org/p/Zs9EK5sinh) in ' case ' a ', ' e ', ' I ', ' o ', ' u ': ' This line lists all the vowels. As long as the item is matched, it will output ' vowel '. # # non-expression switch in the switch statement, the expression is optional and can be omitted. If an expression is omitted, the switch statement is equivalent to ' switch true ', and each ' case ' expression is considered valid and the corresponding code block is executed. "' ' Gopackage mainimport (" FMT ") func main () {num: =/=///expression was omitted case num >= 0 && num <= 50:fmt. PRINTLN ("num is greater than 0 and less than") Case num >= && num <= 100:fmt. PRINTLN ("Num is greater than, and less than,") Case num >= 101:fmt. PRINTLN ("num is greater than 100")}} "[Running Program Online] (Https://play.golang.org/p/mMJ8EryKbN) in the above code, switch is missing an expression, so by default it is The True,true value matches the evaluation result of each case. ' Case num >= wuyi && <= 100: ' Is true, so the program outputs ' num is greater than and less than 100 '. This type of switch statement can override multiple ' if Else ' clauses. # # Fallthrough statement in Go, after each case is executed, it jumps out of the switch statement and does not judge and execute the subsequent case. Use the ' Fallthrough ' statement to transfer control to the execution code of the next case after the completed case has been executed. Let's write a program to understand Fallthrough. Our program will check if the number entered is less than 50, 100, or 200. For example, if we enter 75, the program will output ' lesser than 100 ' and ' 75 is lesser than 200 '. We use Fallthrough to implement this function. "' Gopackage mainimport (" FMT ") func number () int {num: = * 5 return num}func main () {switch num: = number (); {//num is not a constant case num < 50:fmt. Printf ("%d is lesser than 50\n", num) fallthrough case num < 100:fmt. Printf ("%d is lesser than 100\n", num) fallthrough case num < 200:fmt. Printf ("%d is lesser than", Num)}} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/SVGJAISWQJ) switch and case expressions are not necessarily constants. They can also be computed during the run. In the above program, NUM is initialized to the return value of the function ' number () '. When the program runs into switch, the value of the case is calculated. ' Case num < 100: ' results are true, so program output ' is lesser than 100 '. When executed to the next sentence ' Fallthrough ', the program control jumps directly to the first execution logic of the next case, so print out ' is lesser than 200 '. Finally the output of this program will be "' lesser than" is lesser than "* * * ' fallthrough ' statement should be the last statement of the case clause. If it appears in the middle of the case statement, the compiler will error: ' Fallthrough statement out of place ' * * This is also the last part of our tutorial. There is also a switch type called **type switch**. We'll look at this when we learn the interface. I hope you can enjoy this reading. Please leave your valuable comments and suggestions. * * Previous tutorial-[looping] (https://studygolang.com/articles/11924) * * * * Next tutorial-[Arrays and Slices] (https://studygolang.com/articles/12121) * *

via:https://golangbot.com/switch/

Author: Nick Coghlan Translator: Vicever proofreading: Noluye

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

2,627 Reads
Related Article

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.