Home Backend Development Python Tutorial Detailed explanation of the usage of switch statement and select statement in Golang

Detailed explanation of the usage of switch statement and select statement in Golang

Jun 29, 2017 pm 03:30 PM
golang select switch

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是世界上最好的语言") 
}
Copy after login

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") 
}
Copy after login

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!") 
}
Copy after login

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") 
}
Copy after login

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!") 
}
Copy after login

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") 
}
Copy after login

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 !") 
}
Copy after login

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 
 } 
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Avoid errors caused by default in C switch statements Avoid errors caused by default in C switch statements Apr 03, 2025 pm 03:45 PM

A strategy to avoid errors caused by default in C switch statements: use enums instead of constants, limiting the value of the case statement to a valid member of the enum. Use fallthrough in the last case statement to let the program continue to execute the following code. For switch statements without fallthrough, always add a default statement for error handling or provide default behavior.

Best practices for C language default Best practices for C language default Apr 03, 2025 pm 03:48 PM

The best practices of default in C language: place it at the end of the switch statement as the default processing for unmatched values; it is used to handle unknown or invalid values ​​to improve program robustness; avoid duplication with case branches to maintain conciseness; comment clearly on the purpose of the default branch to improve readability; avoid using multiple defaults in one case to maintain clarity; keep the default branch concise and avoid complex operations; consider using enumeration values ​​as case conditions to improve maintainability; in large switch statements, use multiple default branches to handle different situations.

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

See all articles