Search code examples
gogoroutine

How to 'break' or 'continue' in GoRoutine in for loop?


I'm noob in golang. I want to break or continue in GoRoutine which is included in for loop.

Below is my code

for i, m := range something {
  go func(i int, m someModel){
    if m.Name == "AAA" {
      continue;   // Here occurs error
    }

    // Do something
    // which is very long....
  }
}

In vsCode, the error says that "continue not in for statement".

I know that it can be easily solved by (if ~ else) statements, but the 'else' part in my code is too long, which makes the code looks dirty.
I just want to know if there are other ways to solve this.

Thanks.


Solution

  • The function running with the go statement will be out of the context of the main thread, so the continue statement cannot be used here. There are two ways to achieve your goal

    The first way is to start the function through the go statement, the function inside determines if the condition to continue execution is not met, the return statement ends the Routine

    for i, m := range something {
      go func(i int, m someModel){
        if m.Name == "AAA" {
          return // use return
        }
    
        // Do something
        // which is very long....
      }
    }
    

    The second way is to check the data before starting the function through the go statement. If the startup requirements are not met, you can skip it through the continue statement.

    for i, m := range something {
      if m.Name == "AAA" {
        continue   // Check before start
      }
    
      go func(i int, m someModel){
        // Do something
        // which is very long....
      }
    }
    

    Inferring from your code context, I recommend you the second