Let’s continue our discussion of return statements by looking at functions that don’t actually return anything…
Return statements
…
In a function without a result type, a “return” statement must not specify any result values.
func noResult() { return }
Simple enough. Within functions without return values, return
must not include any result values.
But that doesn’t actually mean the example code you see is good code.
In the noResult
function, the return
statement is actually completely redundant, because the function simply ends on the next line.
So for a function with no return values, a return
statement is only necessary if you want to return early.
func warnIfTooLate() {
if time.Now().After(deadline) {
fmt.Println("It's too late!")
return
}
fmt.Println("You still have time")
}
In fact, there are linters, such as gosimple
(also part of golangci-lint) which will complain if you have redundant return statements at the end of such functions. I always recommend linting for such things, as I believe it makes one’s code more readable.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)