A new possible costruct

Hi, I’ve thinked, why can’t exist a construct like for-else?
For example if the condition isn’t true, it can go directly to the else statement.
Tell me if it is a good idea or not. It can be very useful for me!

Can you provide an example how it should work? I really do not understand what you are trying to say…

As it is now, the loops body will be executed 0 to many times, depending on the condition. The code following the loops body will be executed exactly once as soon as the loops condition is false. So for me it seems as if the current default behaviour of loops is already what you want.

For example, if I have to calculate a sum of some numbers, I need an if to check if there are more than 1 number and after I need a for cycle; but if I can do “for(…;numbers>1;…){} else{}” it’s faster and more intuitive, because it will enter in the else costruct only if the number aren’t more than 1, and it can say to the user that it needs more numbers.
Certainly, this is only a stupid example, but it can be applied to other contexts.

No need to. Just initialise your sum to zero and it will work magically. Code sample follows as soon as I’m on a computer.

Go is focused around simplicity and stability, rather than adding lots of clutter to the language to try to please everyone, which has arguably ruined languages like Java, C++, and Javascript.

It might not be as concise, but you can handle it simply by wrapping an if/else around the for loop like this:

if numbers > 1 {
    for numbers > 1 {
        (statements)
    }
} else { (statements) }

To anyone who is used to Go, that’s clear and easy to understand.

2 Likes

From the FAQ: https://golang.org/doc/faq#Why_doesnt_Go_have_feature_X
But you can always open this as a feature request on https://github.com/golang/go/issues if you can motivate this.

golang does support this feature in the text/template package for templates

{{range pipeline}} T1 {{else}} T0 {{end}}
	The value of the pipeline must be an array, slice, map, or channel.
	If the value of the pipeline has length zero, dot is unaffected and
	T0 is executed; otherwise, dot is set to the successive elements
	of the array, slice, or map and T1 is executed.
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.