Break in select won't break the outer for loop

Source: Internet
Author: User
Tags goto
This is a creation in Article, where the information may have evolved or changed.

Background

Background advertising system matching from serial to parallel, involving concurrency control and some resource recovery work, the use of channel to do is very easy to achieve. Detail is the devil, or write less:)

Problematic code example


Problematic code

The code implementation function is simple, the for loop receives N channel data, the business channel transmits the business data, the last ch is used to pass the cancellation signal, if CH receives the data then exits the For loop. According to C-like habit, the ideal output must be this:

Start Cancel

Do something

Do something

Do something

Receive Cancel 0

Over

But the real situation is:

Start Cancel

Do something

Do something

Do something

Receive Cancel:0receive cancel:0 Countless receive cancel:0 into a dead loop

Channel characteristics

Put aside the question first, simply list the characteristics of a channel

1. Buffered channel and unbuffered channel, the difference between buffering or not

2. Writing a closed channel can cause panic

3. Data not consumed after the buffered channel is closed, can be read to the non-consumption data

4. When the channel with no data is closed, you can read the 0 value of that type immediately

Cause of the cycle of death

The channel features listed above are just for dine ~ ~

There are two types of break in Golang, one is break, one is break [label], and the official document is tested with the following conclusions:

1. Break without a label, only the closest loop can be exited, and the switch is invalid for select

2. Break with label, valid for for, select, switch

3. The label of a break can only be attached to a for, select, or switch statement of the same function, and in contrast to the label of Goto is optional

Exit the correct Posture



Break

Or with C-like's goto.


Goto
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.