Home > Article > Backend Development > Why am I Getting \'syntax error: unexpected semicolon or newline before else\' in my Go Code?
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:
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!