-3

In the below code:

data.WaitForGoroutine.Add(1)
go func() {
    for {
        select {
        case msg := <-someCh:
            data.DataCh <- fmt.Sprintf("Received messages: key %s, value: %s\n", string(msg.Key), string(msg.Value))
        case <-data.Signal:
            close(data.DataCh)
            break
        }
    }
    data.WaitForGoroutine.Done()
}()

Linter complains that data.WaitForGoroutine.Done() is unreachable code.

Doesn't break break from for{}?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • Technically, it breaks out of the `select`. If you don't include this break, you can end up triggering multiple cases. – Liftoff Jan 23 '21 at 07:55
  • @David Go does not have fall-through on `switch` and `select` cases. – Hymns For Disco Jan 23 '21 at 17:07
  • @HymnsForDisco, https://golang.org/ref/spec#Fallthrough_statements – JimB Jan 23 '21 at 22:51
  • @JimB Interesting. I know I've seen that keyword before, but forgot about it until now. I should correct: Go does not have fall-through as a default behaviour in `switch` and `select` statements, therefore you don't need `break` to prevent it. – Hymns For Disco Jan 23 '21 at 23:58

1 Answers1

4

Per the spec:

A "break" statement terminates execution of the innermost "for", "switch", or "select" statement within the same function.

Your break terminates the select, not the for. If you want to break out of the for, use labels (same section of the spec). eg:

OuterLoop:
    for {
        select {
        case msg := <-someCh:
            data.DataCh <- fmt.Sprintf("Received messages: key %s, value: %s\n", string(msg.Key), string(msg.Value))
        case <-data.Signal:
            close(data.DataCh)
            break OuterLoop
        }
    }
mkopriva
  • 35,176
  • 4
  • 57
  • 71
Marc
  • 19,394
  • 6
  • 47
  • 51