unexpected semicolon or newline before else even though there is neither before else if

后端 未结 2 1602
不知归路
不知归路 2021-01-17 18:34

I\'m trying to fix these errors in my golang code and if someone could help me with that, I\'d appreciate it.

Here is my code: http://play.golang.org/p/yELWfIdWz5

相关标签:
2条回答
  • 2021-01-17 18:47

    https://golang.org/doc/effective_go.html#if

    You can find the explanation here, but I find it to be a bit bikeshedding. For example, this, unintuitive as it is, compiles:

        if your_age >= 16 {
        say("\n You can earn a Drivers License."); } else
        if your_age >= 18 { say("\n You can vote."); } else
        { say("\n You can have fun."); }
    
    0 讨论(0)
  • 2021-01-17 18:54

    You need to put the 'else' on the line with the close brace in Go.

    Go inserts a ; at the end of lines ending in certain tokens including }; see the spec. That means that, fortunately, it can insert the ending semicolon on x := func(){...} or x := []int{1,2,3}, but it also means it inserts one after the } closing your if block. Since if {...} else {...} is a single compound statement, you can't stick a semicolon in the middle of it after the first }, hence the requirement to put } else { on one line

    It's unusual, but it keeps the semicolon-insertion behavior simple. Having been hit with unexpected program behavior because of the cleverer semicolon insertion rules in another semicolon-optional language, this seems alright in the scheme of things.

    And I can see how the error message was confusing, but 'newline before else' just refers to the newline after the } on the previous line.

    0 讨论(0)
提交回复
热议问题