bmw0128
bmw0128

Reputation: 13698

Golang if/else not compiling

I cannot figure out why this will not compile. It says functions ends without a return statement, but when I add a return after the else, it still won't compile.

func (d Foo) primaryOptions() []string{

if(d.Line == 1){
    return []string{"me", "my"}
}
else{
    return []string{"mee", "myy"}
}
}

Upvotes: 6

Views: 381

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65049

Go forces else to be on the same line as the if brace.. because of its "auto-semicolon-insertion" rules.

So it must be this:

if(d.Line == 1) {
    return []string{"me", "my"}
} else { // <---------------------- this must be up here
    return []string{"mee", "myy"}
}

Otherwise, the compiler inserts a semicolon for you:

if(d.Line == 1) {
    return []string{"me", "my"}
}; // <---------------------------the compiler does this automatically if you put it below
else {
    return []string{"mee", "myy"}
}

..hence your error. I will link to the relevant documentation shortly.

EDIT: Effective Go has information regarding this.

Upvotes: 9

Related Questions