"Si un ouvrier veut bien faire son travail, il doit d'abord affûter ses outils." - Confucius, "Les Entretiens de Confucius. Lu Linggong"
Page de garde > La programmation > Why Am I Getting \"Syntax Error: Unexpected Semicolon Before Else\" in Go?

Why Am I Getting \"Syntax Error: Unexpected Semicolon Before Else\" in Go?

Publié le 2024-11-07
Parcourir:324

Why Am I Getting \

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:

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)
}

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.

Dernier tutoriel Plus>

Clause de non-responsabilité: Toutes les ressources fournies proviennent en partie d'Internet. En cas de violation de vos droits d'auteur ou d'autres droits et intérêts, veuillez expliquer les raisons détaillées et fournir une preuve du droit d'auteur ou des droits et intérêts, puis l'envoyer à l'adresse e-mail : [email protected]. Nous nous en occuperons pour vous dans les plus brefs délais.

Copyright© 2022 湘ICP备2022001581号-3