[go-nuts] break [ label | int_lit ], e.g. break 2

253 views
Skip to first unread message

Troy Beckstrom

unread,
May 10, 2010, 11:04:26 AM5/10/10
to golang-nuts
For breaking out of multiple loops, what do you think about having the
option to specify how many loop levels to break out of as a number,
like this:

for y := 0; y < 100; y++ {
for x := 0; x < 100; x++ {
...
if doneearly {
break 2
}
}
}

It could coexist with break [label] because labels can't start with
numbers.

The advantages:
1) You can specify all of your intent in one place. When you add or
remove break int_lit statements, you don't have to remember to add or
remove labels somewhere else.
2) You don't have to think up a label name.
3) It's more analogous to the way single break and continue work.
4) The code can be copied without having to rename labels.

Rob 'Commander' Pike

unread,
May 10, 2010, 12:09:59 PM5/10/10
to Troy Beckstrom, golang-nuts
I'm surprised you'd prefer a number to a name. I like the computer to do the counting.

-rob

Ostsol

unread,
May 10, 2010, 1:48:30 PM5/10/10
to golang-nuts
Instead of a break to a label you might as well use a goto statement.

-Daniel

mg

unread,
May 11, 2010, 7:42:44 AM5/11/10
to golang-nuts
On May 10, 5:04 pm, Troy Beckstrom <troybeckst...@gmail.com> wrote:
> 2) You don't have to think up a label name.

But then you'd have to add a comment with the same info... ;-)
Alternatively, you could put part of the code into a separate function/
method and use "return".

Troy Beckstrom

unread,
May 11, 2010, 10:46:19 AM5/11/10
to golang-nuts
If you're breaking out of so many levels that you have to "count" then
isn't your function too deep? That kind of break should really be a
"return" or "goto error". Everyone's mind seems to have jumped
straight into the gutter with break 3, 4, 5, etc. I guess you're
right, I wouldn't want to encounter some spaghetti code "break 6".

I was really only thinking about break 2. I've run into a lot of
cases where I just needed to break one more level. Typically, it's
where the condition for breaking requires a scanning loop, but then
the break would be caught by the scanning loop itself.

A syntactic sugar "breakbreak" would give an excuse to only provide 2
levels, if you're afraid more than 2 would be used for evil.

(I guess this idea is doomed anyway on the grounds of providing more
than one way of doing something.)
Reply all
Reply to author
Forward
0 new messages