In Go, you can name the return values in the function signature, and when the function is executed, the values assigned to those named variables are automatically returned. This is particularly useful in short functions, improving readability.
Here's an example:
package main
import "fmt"
func addAndMultiply(a, b int) (sum, product int) {
sum = a + b
product = a * b
// No explicit return values, uses naked return
return
}
func main() {
result1, result2 := addAndMultiply(3, 4)
fmt.Println("Sum:", result1)
fmt.Println("Product:", result2)
}
In this example, the addAndMultiply
function declares named return values sum
and product
in its signature. Inside the function, the values are assigned, and the return
statement is used without specifying the values. This is considered a naked return.