Basic Syntax
To return multiple values, specify the return types in parentheses in the function signature:(int, int) in the signature indicates that this function returns two int values.
Receiving Multiple Return Values
Use multiple assignment to receive all return values:The Blank Identifier
If you only need a subset of the returned values, use the blank identifier_ to ignore unwanted values:
The blank identifier
_ is a write-only variable that allows you to discard values you don’t need. This is particularly useful when a function returns an error you want to ignore (though this is generally not recommended in production code).Complete Example
Common Use Cases
Error Handling
The most common pattern: returning a result and an error
Boolean Checks
Returning a value and a boolean indicating success
Named Return Values
Go also supports named return values, which can make code more readable:Best Practices
Always check errors
Always check errors
When a function returns an error as one of multiple values, always check it:
Return errors last
Return errors last
By convention, error values are returned as the last return value:
Limit the number of return values
Limit the number of return values
While Go supports many return values, keeping them to 2-3 improves readability. Consider using a struct for more complex returns.
Key Takeaways
- Go natively supports returning multiple values from functions
- Use multiple assignment to receive all return values
- The blank identifier
_lets you ignore unwanted values - Multiple returns are commonly used for error handling patterns
- By convention, errors are returned as the last value