Return values are a fundamental concept in Go programming. They allow functions to send data back to the caller, enabling modular and reusable code.
In Go, functions can return zero or more values. The return type is specified after the function parameters:
func functionName(parameters) returnType {
// function body
return value
}
For a single return value, simply declare the type and use the return
keyword:
func add(a, b int) int {
return a + b
}
Go supports returning multiple values from a function, a powerful feature for error handling and complex operations:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
This example demonstrates how to return both a result and an error, a common pattern in Go.
Go allows you to name return values in the function signature. This can improve code readability and simplify the return statement:
func rectangle(width, height float64) (area, perimeter float64) {
area = width * height
perimeter = 2 * (width + height)
return // naked return
}
Named return values are initialized to their zero values and can be directly used in the function body.
To deepen your understanding of Go functions and return values, explore these related topics:
Mastering return values is crucial for writing efficient and idiomatic Go code. Practice using different return patterns to enhance your Go programming skills.