Named return values let you give names to the results a function sends back. This makes your code easier to read and understand.
0
0
Named return values in Go
Introduction
When you want to clearly show what each returned value means.
When a function returns multiple values and you want to avoid confusion.
When you want to write shorter return statements without listing variables again.
When you want to document the purpose of each return value inside the function signature.
Syntax
Go
func functionName(params) (name1 type1, name2 type2) {
// function body
return
}The names in parentheses after the function parameters are the named return values.
You can use a simple return without arguments to return the current values of the named returns.
Examples
This function returns a named result and an error message. It uses named returns to simplify the return statements.
Go
func divide(a, b int) (result int, err string) { if b == 0 { err = "cannot divide by zero" return } result = a / b return }
Here, the function returns two named strings. The
return statement sends back the current values of firstName and lastName.Go
func getName() (firstName, lastName string) {
firstName = "John"
lastName = "Doe"
return
}Sample Program
This program uses a function with named return values to divide two numbers. It shows how the function returns an error message if dividing by zero.
Go
package main import "fmt" func divide(a, b int) (result int, err string) { if b == 0 { err = "cannot divide by zero" return } result = a / b return } func main() { res, err := divide(10, 2) if err != "" { fmt.Println("Error:", err) } else { fmt.Println("Result:", res) } res, err = divide(5, 0) if err != "" { fmt.Println("Error:", err) } else { fmt.Println("Result:", res) } }
OutputSuccess
Important Notes
Named return values act like variables declared at the start of the function.
Using named returns can make your code cleaner but avoid overusing them if it makes the function confusing.
Summary
Named return values give names to the outputs of a function.
They help make your code easier to read and understand.
You can return named values simply by using return without arguments.