Home >Backend Development >Golang >Why Am I Getting \'Unexpected Semicolon or Newline Before Else\' in Go?
Unexpected Semicolon or Newline Before Else in Go
When encountering the error "unexpected semicolon or newline before else," despite an absence of these characters, the issue typically stems from an incorrect placement of the "else" statement. Unlike other languages, Go requires the "else" statement to be placed on the same line as the closing brace of the preceding if block. This ensures that the "else" statement is part of the same compound statement as the if block.
Example:
<code class="go">func main() { if len(s) == 0 { return } else { // Code } }</code>
Explanation:
In the above code, the "else" statement is placed on a separate line from the closing brace of the if block, which is incorrect. To fix this, the "else" statement must be moved onto the same line as the closing brace:
<code class="go">func main() { if len(s) == 0 { return } else { // Code } }</code>
Additional Errors
The error messages on lines 28 and 32, indicating "non-declaration statement outside function body," suggest that there may be statements outside the main() function that should be declared as functions or moved inside the main() function body.
Conclusion:
By addressing the placement of the "else" statement and potential extra statements outside the main() function, these errors can be resolved, allowing the code to run as intended.
The above is the detailed content of Why Am I Getting \'Unexpected Semicolon or Newline Before Else\' in Go?. For more information, please follow other related articles on the PHP Chinese website!