Why is only "if", but not "for" and "switch", allowed to follow "else" keyword?

190 views
Skip to first unread message

tapi...@gmail.com

unread,
Oct 6, 2020, 1:27:47 PM10/6/20
to golang-nuts
IMO, the bar function is cleaner and more readable than the foo function.
How do you think?

    func foo() {
        if vs := f(); len(vs) == 0 {
        } else {
            for _, v := range vs {
            }
        }
       
        if vs := f(); len(vs) == 0 {
        } else {
            switch {
            case len(bs) == 0:
            case len(bs) == 1:
            default:
              }
        }
    }

    // vs.

    func bar() {
        if vs := f(); len(vs) == 0 {
        } else for _, v := range vs {
        }
       
        if vs := f(); len(vs) == 0 {
        } else switch {
        case len(vs) == 0:
        case len(vs) == 1:
        default:
        }
    }

Jan Mercl

unread,
Oct 6, 2020, 1:42:00 PM10/6/20
to tapi...@gmail.com, golang-nuts
IMO opinion the answer is nicely demonstrated in the alignment of sone of the closing braces you've chosen in the func bar example.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/6b6d44d7-2ce5-4cd0-9347-88b350715088n%40googlegroups.com.

Ian Lance Taylor

unread,
Oct 6, 2020, 1:54:16 PM10/6/20
to tapi...@gmail.com, golang-nuts
Well, why stop there? Why not

if vs := f(); len(vs) == 0 {
} else f2()

if vs := f(); len(vs) == 0 {
} else x = y

There is a simple rule:
if <condition> <block> [else <block>]
In fact, for a while in the very early days of Go, that was the only
rule. But experience showed that people naturally want to write
if/else if/else, and having to add extra braces was frustrating, and
they tended to stack up. So the rule was extended to (roughly):
if <condition> <block> [else if <condition> <block> [else <block>]]

There's no obvious need to extend the rule in any other way. It's not
something that people are running into.

Ian

tapi...@gmail.com

unread,
Oct 6, 2020, 2:27:54 PM10/6/20
to golang-nuts
These are different. "for" and "switch" are both code block start keywords, just the same as "if".
Reply all
Reply to author
Forward
0 new messages