Home >Backend Development >Golang >Why am I getting the \'unexpected semicolon or newline before else\' error in my Go code?

Why am I getting the \'unexpected semicolon or newline before else\' error in my Go code?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 19:17:02976browse

Why am I getting the

Unexpected semicolon or newline before else

The error "unexpected semicolon or newline before else" occurs when there is a semicolon or newline character before the else keyword in an if-else statement. In the code provided, the error is on line 21:

for err == nil{
    subject, predicate, object := parseTriple(line)
    if subject == current_mid{
        current_topic[predicate] = append(current_topic[predicate], object)
    }
    else if len(current_mid) > 0{
        processTopic(current_mid, current_topic, xmlFile)
        current_topic = make(map[string][]string)
    }
    current_mid = subject
    line, err = r.ReadString('\n')
}

In this case, there is a newline character after the closing brace of the if block, which is causing the error. To fix the error, the else if statement should be placed on the same line as the closing brace:

for err == nil{
    subject, predicate, object := parseTriple(line)
    if subject == current_mid{
        current_topic[predicate] = append(current_topic[predicate], object)
    } else if len(current_mid) > 0{
        processTopic(current_mid, current_topic, xmlFile)
        current_topic = make(map[string][]string)
    }
    current_mid = subject
    line, err = r.ReadString('\n')
}

Explanation:

In Go, the semicolon is used to terminate statements. However, Go also automatically inserts a semicolon at the end of certain lines, including lines that end with a closing brace }. This means that if you have an if block that spans multiple lines, you must put the else statement on the same line as the closing brace, or else Go will insert a semicolon after the closing brace and cause a syntax error.

The error messages on lines 28 and 32 ("non-declaration statement outside function body") are also caused by the error on line 21. The closing brace on line 21 is not properly terminated, so Go is treating the lines after it as if they are outside of the main function. To fix these errors, you must first fix the error on line 21.

The above is the detailed content of Why am I getting the \'unexpected semicolon or newline before else\' error 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