


Detailed explanation of the usage of switch statement and select statement in Golang
This article mainly introduces you to the usage tutorial of switch and select in Golang. The article introduces the usage of switch statement and select statement in great detail through sample code, which is of certain significance to everyone. Referring to the value of learning, friends in need can follow the editor to learn together.
This article mainly introduces to you the relevant content about the usage of switch and select in Golang, and shares it for your reference and study. Let’s take a look at the detailed introduction:
1. Switch statement
# The switch statement provides a multi-branch conditional execution method. Each case can carry an expression or a type specifier. The former can also be referred to as a case expression. Therefore, the switch statement in Go language is divided into expression switch statement and 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是世界上最好的语言") }
Go will evaluate each case in order from top to bottom The case expression in the statement is evaluated. As long as the expression is found to have the same result as the switch expression, the case statement will be selected. The rest of the case statements will be ignored. Like if, the switch statement can also contain initialization words, and their appearance and writing are exactly the same:
names := []string{"Golang","java","PHP"} switch name:=names[0];name { case "Golang": fmt.Println("Golang") ... default: fmt.Println("Unknown") }
2. Type switch statement
Type switch statement has two differences from the general form. The first point is that what follows the case keyword is not an expression, but a type specifier. A type specifier consists of several type literals, and multiple type literals are separated by commas. The second point is that its switch expression is very special. This special expression also plays the role of type assertion, but its expression is very special, such as: v.(type)
, where v must represent a value of type interface . This type of expression can only appear in type switch statements and can only serve as switch expressions. An example of a type switch statement is as follows:
v := 11 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 way, we can use this result in the switch statement. After this code is executed, the output is: "A signed integer:11. The type is int.
"
Finally, let’s talk about fallthrough. It is both a keyword and can represent a statement. A fallthrough statement can be included in a case statement within an expression switch statement. Its function is to transfer control to the next case. However, please note that the fallthrough statement can only appear as the last statement in the case statement. Moreover, the case statement containing it is not the last case statement of the switch statement to which it belongs.
2. Select statement
Golang’s select function is similar to select, poll, and epoll, which is to monitor IO Operation, when an IO operation occurs, the corresponding action is triggered.
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") }
Notice that the code form of select is very similar to switch, but the operation statement in the case of select can only be [ IO operation].
In this example, select will wait until a certain case statement is completed, that is, until the data is successfully read from ch1 or ch2. The select statement ends.
The break statement can also be included in the case statement in the select statement. Its function is to immediately end the execution of the current select statement. Regardless of whether there are any unexecuted statements in the case statement to which it belongs.
[Use select to implement timeout mechanism]
is as follows:
timeout := make(chan bool, 1) go func() { time.Sleep(time.Second * 10) timeout <- true }() select { case <-pssScanResponseChan: case <-timeout: fmt.PrintIn("timeout!") }
When the timeout time expires, case2 will operate successfully. So the select statement will exit. Instead of always blocking on the read operation of ch. This implements the timeout setting for ch read operations.
The following one is more interesting.
When the select statement contains default:
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") default: fmt.Println("default") }
At this time, because both ch1 and ch2 are empty, neither case1 nor case2 Will read successfully. Then select executes the default statement.
Because of this default feature, we can use the select statement to detect whether chan is full.
is as follows:
ch := make (chan int, 1) ch <- 1 select { case ch <- 2: default: fmt.Println("channel is full !") }
Because ch is already full when 1 is inserted. When ch is about to insert 2, it is found that ch is already full. (case1 is blocked), then select executes the default statement. In this way, it is possible to detect whether the channel is full instead of waiting all the time.
For example, if we have a service, when a request comes in, we will generate a job and throw it into the channel, and other coroutines will get the job from the channel for execution. But we hope that when the channel is hidden, we will abandon the job and reply [The service is busy, please try again later. ] You can use select to achieve this requirement.
此外,利用default特性,我们可以使用select语句将chan清空,如下:
flag := false for { select { case <-pssScanResponseChan: continue default: flag = true } if true == flag { break } }
The above is the detailed content of Detailed explanation of the usage of switch statement and select statement in Golang. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)