How to Use Named Return Values in Go: Syntax and Examples
named return values by specifying names for the return variables in the function signature. These names act like local variables and can be assigned within the function, allowing you to use a simple return statement without arguments to return their values.Syntax
Named return values are declared in the function signature by giving each return type a name. Inside the function, these names behave like variables that you can assign values to. When you use a bare return statement, Go returns the current values of these named variables.
- func: keyword to declare a function
- functionName: the name of the function
- (parameters): input parameters
- (namedReturns): named return variables with types
- return: bare return returns the named variables
func functionName(params) (name1 type1, name2 type2) {
// assign values to name1, name2
return // returns name1, name2 automatically
}Example
This example shows a function that calculates the sum and product of two integers using named return values. The function assigns values to the named returns and uses a bare return to send them back.
package main import "fmt" func sumAndProduct(a, b int) (sum int, product int) { sum = a + b product = a * b return // returns sum and product } func main() { s, p := sumAndProduct(3, 4) fmt.Printf("Sum: %d, Product: %d\n", s, p) }
Common Pitfalls
One common mistake is to declare named return values but then also return explicit values, which can cause confusion or redundancy. Another is forgetting that named return variables are zero-initialized, so if you don't assign them, the function returns zero values silently.
Also, overusing named returns can reduce code clarity if the function is long or complex.
package main // Wrong: mixing named returns with explicit return values func wrongExample() (result int) { result = 5 return 10 // explicit return overrides named return } // Correct: use either named returns with bare return or explicit return func correctExample() (result int) { result = 5 return // returns 5 } func main() { println(wrongExample()) // prints 10 println(correctExample()) // prints 5 }
Quick Reference
- Declare named return values in the function signature inside parentheses.
- Assign values to these named variables inside the function body.
- Use a bare
returnto return all named values automatically. - Named returns are zero-initialized if not assigned.
- Use named returns for clarity in short functions, avoid in long functions.