How to Return Early from a Function in Go
A Go function normally runs to its last line, but return ends it at once. In a function that returns nothing, a plain return with no value is how you leave early, for example right after handling a case that needs nothing more.
Syntax
func <name>(<parameters>) {
if <condition> {
<handle the case>
return
}
<the rest of the function>
}
| Part | What it does |
|---|---|
return | Ends the function immediately; nothing after it in the function runs. |
| No result type | The function returns nothing, so return must not have a value. |
The Go language specification on return statements: "In a function without a result type, a "return" statement must not specify any result values."
The Example
The example has a greet function that returns nothing. When the name is empty, it prints a message and returns early; otherwise it goes on to greet the person. main calls it with a name and without one.
Prerequisites
- Go.
go runcompiles and runs a single file. This guide uses Go 1.27.4.
Step 1: Write the Code
Create a file named main.go:

package main
import "fmt"
func greet(name string) {
if name == "" {
fmt.Println("No name given.")
return
}
fmt.Println("Hello, " + name + "!")
}
func main() {
greet("Ada")
greet("")
}
Step 2: Run It
go run main.go
Hello, Ada!
No name given.

The command is the same in zsh, bash and PowerShell.
What Happened
greet("Ada")skipped theifblock and printed the greeting.greet("")entered theifblock, printed its message, andreturnended the function before the greeting line.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Returning a value from a function without a result type | It doesn't compile: too many return values, with have (string) and want () | Remove the value, or give the function a result type |
Forgetting the return in the guard | The function goes on and runs the code meant for the other case | End the guard block with return |
Nesting the main work inside else | The code drifts right and gets harder to read | Return early and keep the main path unindented |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
too many return values | return has a value in a function with no result type | Drop the value |
| Both messages printed for one call | The guard block has no return | Add return at the end of the guard |
FAQ
Can I return early from main?
Yes. return in main ends the program normally, with exit code 0. To end with another code, use os.Exit.
What about functions that return a value?
There, every return needs values for the results, as in return "", err in a function that returns a string and an error.
Conclusion
return on its own leaves a Go function that returns nothing, right away. Use it at the end of a guard clause so the special case is handled and done, and the rest of the function stays simple.
Additional Resources
- Return statements, in the Go language specification.
