Unexpected Semicolon Before Else in Go: A Detailed Explanation
Your Go code encounters an unusual error on line 21: "syntax error: unexpected semicolon or newline before else." Despite your assertion, closer examination reveals that there is indeed a semicolon (;) before the "else" statement on this line.
The core problem here stems from Go's automatic semicolon insertion rule. Normally, semicolons are optional in Go; however, the compiler will automatically insert them at the end of certain lines to maintain syntactical integrity. One such case is when a line concludes with a closing brace '}', such as the one that closes the "if" statement on line 21.
This behavior poses an obstacle for the subsequent "else" statement. In Go, the "else" block should be written on the same line as the closing brace of the "if" statement. Therefore, the compiler cannot add a semicolon at the end of line 21 because it would create two separate statements, which is incorrect syntax.
To resolve this issue, place the "else" keyword directly after the closing brace on line 21:
<code class="go">if subject == current_mid { current_topic[predicate] = append(current_topic[predicate], object) } else { processTopic(current_mid, current_topic, xmlFile) current_topic = make(map[string][]string) }</code>
This modification ensures that the "if" and "else" statements form a single compound statement, as required by Go's syntax.
Regarding the errors on lines 28 and 32, they relate to statements outside the "main" function's scope. In Go, statements must be enclosed within the body of the function they belong to. To fix these errors, include the statements within curly braces '}' within the "main" function's body.
The above is the detailed content of Why Am I Getting 'Syntax Error: Unexpected Semicolon Before Else' in Go?. For more information, please follow other related articles on the PHP Chinese website!