Function Return Basics
Understanding Function Returns in Golang
In Golang, functions can return multiple values, which is a powerful and unique feature compared to many other programming languages. This flexibility allows developers to write more expressive and concise code.
Basic Return Syntax
A typical Golang function return follows this basic syntax:
func functionName(parameters) (returnType1, returnType2) {
// Function body
return value1, value2
}
Simple Single Return Example
func add(a, b int) int {
return a + b
}
func main() {
result := add(5, 3)
fmt.Println(result) // Outputs: 8
}
Multiple Return Values
Golang allows functions to return multiple values, which is extremely useful for returning results and errors:
func divideNumbers(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divideNumbers(10, 2)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
Return Value Types
Golang supports returning different types of values:
Return Type |
Description |
Example |
Single Value |
Traditional single return |
func() int |
Multiple Values |
Return multiple results |
func() (int, string) |
Named Returns |
Pre-declared return variables |
func() (x int, y string) |
Named Return Values
Functions can use named return values for improved readability:
func calculateStats(numbers []int) (count int, sum int, average float64) {
count = len(numbers)
for _, num := range numbers {
sum += num
}
average = float64(sum) / float64(count)
return
}
Workflow of Function Returns
graph TD
A[Function Call] --> B{Check Return Values}
B --> |Single Return| C[Use Returned Value]
B --> |Multiple Returns| D[Handle Multiple Values]
D --> E[Check for Errors]
E --> |Error Exists| F[Handle Error]
E --> |No Error| G[Process Results]
Best Practices
- Always handle potential errors
- Use multiple returns for complex operations
- Keep return signatures clear and consistent
- Prefer explicit returns over implicit ones
By mastering function returns, you'll write more robust and readable Golang code. LabEx recommends practicing these patterns to improve your programming skills.