Home  >  Article  >  Backend Development  >  Why am I Getting \"syntax error: unexpected semicolon or newline before else\" in my Go Code?

Why am I Getting \"syntax error: unexpected semicolon or newline before else\" in my Go Code?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 12:40:02178browse

Why am I Getting

Unforeseen Syntax Error: Unexpected Semicolon or Newline Before "Else" in Go

The Go compiler reports an enigmatic error message: "syntax error: unexpected semicolon or newline before else." Despite a thorough inspection of line 21, the code appears to lack any offending semicolons or newlines.

Delving deeper, we uncover two additional puzzling errors on lines 28 and 32: "non-declaration statement outside function body." These statements reside within the main() function and should be unaffected by the closing brace terminating the function.

Evidence suggests that the aforementioned errors stem from an underlying issue in line 21. The Go language introduces some unique semicolon-handling behavior:

  • Semicolons are automatically inserted at the end of lines containing specific tokens, including closing braces }.
  • As a result, a semicolon is added after the closing brace of an if block.
  • For if {...} else {...} statements, this semicolon insertion creates a syntax error, as semicolons are not permitted within the else clause.

To resolve this issue, the else clause must be placed on the same line as the closing brace of the if block. For instance:

if len(current_mid) > 0 {
    processTopic(current_mid, current_topic, xmlFile)
} else {
    current_topic = make(map[string][]string)
}

The compiler error concerning "non-declaration statement outside function body" arises from Go's strict requirement that statements outside function bodies be declarations. In the case of lines 28 and 32, the expressions are neither declarations nor part of the function body, hence the error messages.

The above is the detailed content of Why am I Getting \"syntax error: unexpected semicolon or newline before else\" in my Go Code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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