Home > Backend Development > Golang > Why Am I Getting \'Unexpected Semicolon or Newline Before Else\' in Go?

Why Am I Getting \'Unexpected Semicolon or Newline Before Else\' in Go?

Mary-Kate Olsen
Release: 2024-11-02 23:55:29
Original
232 people have browsed it

Why Am I Getting

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template