Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Encountered a strange 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

like image 596
Anuj Verma Avatar asked Aug 15 '11 06:08

Anuj Verma


People also ask

How do I change the bracket in IntelliJ?

From the IntelliJ documentation: Go to the menu File | Settings | Project Settings | Code Style - Java. Select the 'Wrapping and braces' tab. Set 'Braces placement options' to 'Next line'.


3 Answers

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?

like image 188
Esko Luontola Avatar answered Oct 25 '22 21:10

Esko Luontola


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.

like image 33
Peter Varga Avatar answered Oct 25 '22 20:10

Peter Varga


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)."

like image 41
moraes Avatar answered Oct 25 '22 22:10

moraes