Explain the use of switch statements and SELECT statements in Golang

Source: Internet
Author: User
Tags case statement golang tutorial
This article mainly introduces you to the use of switch and select in the Golang tutorial, the article through the example code to the switch statement and select statement using methods introduced in very detailed, for everyone has a certain reference learning value, The friends who need to follow the small series to learn together.

This article mainly introduces to you about the Golang switch and select usage of relevant content, share out for everyone to refer to the study, the following to see a detailed introduction:

One, switch statement

The switch statement provides a way to perform a multi-branch condition. Each case can carry an expression or a type descriptor. The former can also be referred to as the case expression. Therefore, the switch statement of the go language is divided into the expression switch statement and the type switch statement.

1. Expression switch statement


var name string ... switch name {case "Golang":  fmt. Println ("Golang") Case "Rust":  fmt. Println ("Rust") Default:  FMT. Println ("PHP is the best language in the World")}

Go will evaluate the case expression in each of the cases in order from top to bottom, as long as the expression is found to be the same as the result of the switch expression, which will be selected. The remaining case statements are ignored. As with if, the switch statement can also contain initialization words, where they appear and are written in the same way:


Names: = []string{"Golang", "Java", "PHP"} switch name:=names[0];name {case "Golang":  fmt. Println ("Golang") ... default:  FMT. Println ("Unknown")}

2. Type switch statement

The type switch statement has a two-point difference from the general form. The 1th, followed by the case keyword is not an expression, but a type specifier. A type specifier consists of several type literals, separated by commas between multiple type literals. 2nd, its switch expression is very special. This special expression also acts as a type assertion, but its representation is special, such as: v.(type) where v must represent a value of an interface type. The class expression can only appear in a type switch statement and can only act as a switch expression. An example of a type switch statement is as follows:


V: = One switch I: = interface{} (v). (type) {case int, int8, Int16, Int32, Int64:  FMT. PRINTLN ("A signed integer:%d. The type is%T. \ n ", V, i) case uint, uint8, uint16, UInt32, UInt64:  fmt. Println ("A unsigned integer:%d. The type is%T. \ n ", V, i) default:  FMT. Println ("unknown!")}

Here we assign the result of the switch expression to a variable. In this case, we can use this result in the switch statement. After this code is executed, the output: " A signed integer:11. The type is int. "

Finally, say a little bit about Fallthrough. It is both a keyword and a statement. The Fallthrough statement can be included in the case statement in the expression switch statement. Its role is to allow control to flow to the next case. Note, however, that the Fallthrough statement can only appear as the last statement in a case statement. Also, the case statement that contains it is not the last case statement of the switch statement to which it belongs.

Second, select statement

The function of the Golang Select, similar to the Select, poll, Epoll, is to listen to the IO operation and trigger the corresponding action when the IO operation occurs.

Example:


CH1: = Make (chan int, 1) CH2: = Make (chan int, 1) ...  Select {Case <-CH1:  fmt. Println ("ch1 pop One Element") Case <-CH2:  fmt. Println ("CH2 pop One Element")}

Note that the code form for select is very similar to switch, but the action statement in Select's case can only be an "IO operation".

In this example, select waits until a case statement is completed, that is, until the data is read successfully from CH1 or CH2. The SELECT statement ends.

The break statement can also be included in the case statement in the SELECT statement. Its role is to immediately end the execution of the current SELECT statement. Whether or not there are statements that are not executed in the case statement to which they belong.

"Using Select to implement the timeout mechanism"

As follows:


Timeout: = Make (chan bool, 1) go func () {Time  . Sleep (time. Second *)  timeout <-true} () Select {case <-pssscanresponsechan: Case  <-timeout:  fmt. Printin ("timeout!")}

When the time-out expires, the CASE2 operation succeeds. So the SELECT statement exits. Instead of always blocking the read operation on Ch. Thus, the time-out setting for CH read operation is realized.

The following is a more interesting point.

When the SELECT statement has default:


CH1: = Make (chan int, 1) CH2: = Do (chan int, 1)  Select {case <-CH1:  fmt. Println ("ch1 pop One Element") Case <-CH2:  fmt. Println ("CH2 pop One Element") Default:  FMT. PRINTLN ("Default")}

At this point, because both CH1 and CH2 are empty, neither CASE1 nor Case2 will read successfully. The select executes the default statement.

Because of this default feature, we can use the SELECT statement to detect if Chan is full.

As follows:


CH: = Make (chan int, 1) ch <-1 Select {Case ch <-2:default:  fmt. PRINTLN ("Channel is full!")}

Because CH inserted 1 is full, when CH to insert 2, and found that Ch is full (case1 blocked), select executes the default statement. This allows for detection of whether the channel is full, rather than waiting.

For example, we have a service, and when the request comes in, we generate a job to throw into the channel, which is executed by other co-processes from the channel to get the job. But we hope that when the channel is concealed, the job is discarded and replied, "The service is busy, please try again." "You can use Select to implement this requirement.

In addition, using the default feature, we can use the SELECT statement to empty Chan, as follows:


Flag: = False for {  Select {case  <-pssscanresponsechan:  continue  default:  flag = True  }  if True = = Flag {break  }}
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.