foreword
This is the fourth part of the series of top ten common mistakes in Go: Precautions for for/switch and for/select to do the break operation and exit. The material comes from Teiva Harsanyi , a Go evangelist and now a senior engineer at Docker.
The source code involved in this article is all open source in: The source code of the top ten common errors in Go , you are welcome to pay attention to the public account and get the latest updates of this series in time.
Scenes
Case 1
Take a look at the following code:
for {
switch f() {
case true:
break
case false:
// Do something
}
}
What happens if the function call f()
returns true
and enters the case true
branch? Will it exit the for loop?
The answer is: only the switch statement is exited, and the for loop is not exited, so the code in the for loop continues to be executed after break.
Case 2
Look at the following code
for {
select {
case <-ch:
// Do something
case <-ctx.Done():
break
}
}
Similarly, if the break statement is executed, only the select statement block is exited, and the for loop is not exited.
In the above two scenarios, how to exit the for loop?
It can be implemented in combination with label and break.
loop:
for {
select {
case <-ch:
// Do something
case <-ctx.Done():
break loop
}
}
For the above code, loop is a label, break loop
if executed, it will exit the for loop.
Recommended reading
- Top 10 common mistakes in Go Part 1: Unknown enum value
- Top Ten Common Errors in Go Part 2: The pit of benchmark performance testing
- Top 10 Common Go Errors Part 3: Go Pointer Performance Issues and Memory Escape
- Instructions for use of Go switch
- Go for/break Instructions
- Go select semantics
open source address
Articles and sample code are open sourced on GitHub: Beginner, Intermediate, and Advanced Tutorials in Go .
Official account: coding advanced. Follow the official account to get the latest Go interview questions and technology stacks.
Personal website: Jincheng's Blog .
Zhihu: Wuji .
Welfare
I have compiled a back-end development learning material package for you, including programming language entry to advanced knowledge (Go, C++, Python), back-end development technology stack, interview questions, etc.
Follow the official account "coding advanced", send a message backend to receive a gift package, this information will be updated from time to time, and add information that I think is valuable. You can also send a message "join the group " to communicate and learn with your peers and answer questions.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。