头图

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

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.

References


coding进阶
116 声望18 粉丝