Why does Golang enforce curly bracket to not be on the next line?

前端 未结 3 1778
野趣味
野趣味 2021-02-01 15:14

correct:

if(true) {

}

incorrect:

if(true)
{

}

Why is this style enforced, does it have something to do with

3条回答
  •  清歌不尽
    2021-02-01 15:15

    Most C descended languages use the style if ( ) , the statement is executed if condition is true. The statement can be either a single statement or brace enclosed block.

    Go's if statements require a following brace enclosed block, not a single statement. This is to head off a common error that most style guides try to avoid by requiring that all if statements use braces.

    //subtle error in C
    if ()
      ;
      ;
    

    Now that Go requires a brace block following the if statement the () are redundant. They only serve to help the lexer differentiate between the condition and the statement, otherwise if is hard to parse. (Where does the condition end and the statement begin?)

    Now Go's authors have a decision to make:

    • Keep the redundant ()
    • require { to follow the

    They decided redundancy was not desirable. This had a second side effect. Since there is an implicit ; at every newline, if the { is on the following line a ; gets put between the and the {. Go's authors again are faced with a decision:

    • special case the parser to be smart about the ; { construct
    • require everyone adopt a common style of if ... { on the same line.
    • require that the be on a single line.

    Special casing the parser is a very bad thing. Look at the speed D and Go parsers compared to C++'s terrible parser performance. Also a uniform style is a good thing. Their ultimate decision is pretty simple given the constraints.

提交回复
热议问题