Returning Multiple Values
Multiple Return Values in Variadic Functions
Golang allows variadic functions to return multiple values, providing flexibility and expressiveness in function design. This feature enables more complex and informative return patterns.
Basic Multiple Return Syntax
func calculateStats(numbers ...int) (int, int, float64) {
if len(numbers) == 0 {
return 0, 0, 0.0
}
sum := 0
for _, num := range numbers {
sum += num
}
average := float64(sum) / float64(len(numbers))
max := numbers[0]
for _, num := range numbers {
if num > max {
max = num
}
}
return sum, max, average
}
Handling Multiple Return Values
func main() {
total, maximum, avg := calculateStats(10, 20, 30, 40, 50)
fmt.Printf("Total: %d, Maximum: %d, Average: %.2f\n", total, maximum, avg)
}
Return Value Patterns
Pattern |
Description |
Example Use Case |
Multiple Typed Returns |
Different return types |
Statistical calculations |
Error and Result |
Returning value with error |
Database operations |
Optional Returns |
Conditional return values |
Parsing operations |
Advanced Multiple Return Example
func processData(data ...string) ([]string, int, error) {
if len(data) == 0 {
return nil, 0, errors.New("no data provided")
}
processedData := make([]string, 0)
for _, item := range data {
processedData = append(processedData, strings.ToUpper(item))
}
return processedData, len(processedData), nil
}
Error Handling with Multiple Returns
func main() {
result, count, err := processData("hello", "world")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Processed Data: %v, Count: %d\n", result, count)
}
Variadic Function Return Flow
graph TD
A[Variadic Function Call] --> B[Process Arguments]
B --> C{Validation}
C -->|Valid| D[Compute Results]
D --> E[Return Multiple Values]
C -->|Invalid| F[Return Error]
Best Practices
- Use named return values for clarity
- Always handle potential errors
- Keep return values meaningful and consistent
- Prefer explicit over implicit returns
- Multiple return values have minimal overhead
- Use when it improves code readability
- Avoid excessive complexity
At LabEx, we encourage developers to leverage Golang's multiple return capabilities to write more expressive and robust code.