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

后端 未结 2 1603
不知归路
不知归路 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: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.

提交回复
热议问题