Help us understand the problem. What is going on with this article?

[Go] for { select { default: break } } ではループを抜けられない

過去の自分を含め、意外と間違っている人が多いのですが、

for {
    select {
    default:
        break
    }
}

では for ループを抜けることができません。
これは switch の case や default 内で break を使っても switch は抜けらますが、その外側のループは抜けられないことと同じです。

恐らく default では例外処理を行うことが多く、例外処理のテストを適切に行っていないためこのバグが潜在しているものと思われます。

そこで、Labeled Break を使いましょう!

L:
    for {
        select {
        default:
            break L
        }
    }

これでラベルの貼られた for から break L で抜けることができます。

あ、func で包んで即実行してもいいですが Labeled Break のほうがより直感的ですね。

cia_rana
Go言語/Ruby/渋谷で働くそふとうぇあえんじにゃーん/ Creator Support Engineer
https://medium.com/@cia_rana/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした