Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang if/else not compiling

Tags:

go

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"}
}
}
like image 304
bmw0128 Avatar asked Jun 17 '14 03:06

bmw0128


1 Answers

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.

like image 141
Simon Whitehead Avatar answered Sep 29 '22 06:09

Simon Whitehead