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

零下一度
Release: 2017-06-29 15:30:28
Original
1909 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template