开发者

Why can't I put the opening braces on the next line?

Encountered a stran开发者_运维技巧ge error when I tried to compile following code:


    package main

    import fmt "fmt"

    func main()
    {
       var arr [3]int
       for i:=0; i<3; i++
       {
         fmt.Printf("%d",arr[i])
       }
    }

Error is as follows:


    unexpected semicolon or newline before {

After correction following code worked:


    package main

    import fmt "fmt"

    func main(){
       var arr [3]int
       for i:=0; i<3; i++{
         fmt.Printf("%d",arr[i])
       }
    }

Is GO language this much strictly Typed? And this doesn't have warnings also. Should this not be a programmers choice how he wants to format his code? Go language warnings and errors


The Go language does automatic semicolon insertion, and thus the only allowed place for { is at the end of the preceding line. Always write Go code using the same style as gofmt produces and you will have no problems.

See Go's FAQ: Why are there braces but no semicolons? And why can't I put the opening brace on the next line?


go language includes semicolons with a specific rule, in your case, the newline after the i++ introduces a semicolon before the '{'. see http://golang.org/doc/go_spec.html.

formatting is somewhat part of the language, use gofmt to make code look similar, however, you can format your code many different ways.


Should this not be a programmers choice how he wants to format his code?

Maybe. I think it is nice that Go steps forward to avoid some bike-shedding, like never ending style discussions. There is even a tool, gofmt, that formats code in a standard style, ensuring that most Go code follows the same guidelines. It is like they were saying: "Consistency everywhere > personal preferences. Get used to it, This Is Good(tm)."


Go code has a required bracing style. In the same way that a programmer can't choose to use braces in python and is required to use indentation.

The required bracing style allows the semicolon insertion to work without requiring the parser to look ahead to the next line(which is useful if you want to implement a REPL for GO code)

package main

func main();

is valid Go code and without looking at the next line the parser assumes this is what you meant and is then confused by the block that isn't connected to anything that you've put after it.

Having the same bracing style through all Go code makes it a lot easier to read and also avoids discussion about bracing style.


Go lang fallows strict rules to maintain the unique visibility for the reader like Python, use visual code IDE, it will do automatic formatting and error detection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜