Is this supposed to be an error?


(Sean Killian) #1

I’m writing some Go for the first time outside of an IDE and am not getting immediate feedback for my syntax and semantic errors, so after finally attempting a build and going through tens of errors, I hit one that though I understand what it’s telling me, I don’t understand why it’s an error. I put a reproducible scenario together in the playground here.

For those who don’t click, here’s my test function:

func test() error {
	return nil
	fmt.Println("useless")
}

This produces a compile-time error: “missing return at end of function.” Like I said, I understand what this is telling me, but why is this an error? If I instead change the function to:

func test() {
	return
	fmt.Println("useless")
}

There’s no error.

I’ve been skimming through the language specification here but I still can’t yet tell why not having a return statement at the end is an error if the code is unreachable; it doesn’t surprise me considering how strict Go is about unused variables, imports, etc., but is that specified anywhere?


(Johann Forster) #2

The compiler does not ignore the unreachable code.

func test() error {
	// return nil
	fmt.Println("useless")
}

func test() {
	// return
	fmt.Println("useless")
}

The first function can not be compiled as the function is expected to return an error.
For functions without return values, the return statement is implicit generated if not given.


(Sean Killian) #3

Thanks, @j-forster, after that bit of guidance, I was able to find the relevant part of the spec: https://golang.org/ref/spec#Terminating_statements