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

A strange error was detected when I tried to compile the 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:

     unexpected semicolon or newline before {

After fixing the working code:

     package main

     import fmt "fmt"

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

Is the GO language strongly typed? And there are no warnings in this either. If this is not the choice of programmers, how does he want to format his code? Go to language warnings and errors

+1
source share
4 answers

The Go language performs automatic semicolon insertion, and so the only valid place for { is at the end of the previous line. Always write Go code using the same style as gofmt and you will have no problem.

See the Frequently Asked Questions section: Why are there brackets but no semicolons? And why can't I place an open shape on the next line?

+8
source

go includes semicolons with a specific rule, in your case a new line after I ++ enters a semicolon before '{'. see http://golang.org/doc/go_spec.html .

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

+7
source

Go code has the required binding style. Just like a programmer, there is no way to use curly braces in python, and indentation is required.

The required binding style allows you to use the function with a semicolon, without requiring the parser to look forward to the next line (which is useful if you want to implement REPL code for GO)

 package main func main(); 

is a valid Go code, and without looking at the next line, the parser assumes that this is what you had in mind, and then gets confused by a block that is not associated with anything that you put after it.

Having the same commit style across all Go code makes it much easier to read, and also avoids discussing the binding style.

+2
source

If this is not the choice of programmers, how does he want to format his code?

May be. I think it's good that Go takes a step forward to avoid any kind of bike, like endless discussions of style. There is even a gofmt tool that formats code in a standard style, ensuring that most Go codes follow the same guidelines. This is similar to what they said: "Consistency is everywhere" personal preference. Get used to it, that's good (tm). "

+1
source

Source: https://habr.com/ru/post/1391264/