Go•Functions
Go Multiple Return Values and Error Handling Signatures
Multiple return values are an architectural cornerstone of Go, enabling the idiomatic (T, error) pattern that replaces try/catch exception systems with explicit, predictable control flow. Functions can return any number of typed values, optionally using named return parameters for self-documenting APIs.
Syntax
func calculateMetrics(load int, capacity int) (int, float64, error) {
return used, ratio, nil
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| (T1, T2, ...) | Return Signature | Defines multiple typed return values enclosed in parentheses. |
| error | Built-in Interface | Standard Go interface indicating error state (nil signifies success). |
| Named Returns | Feature | Pre-allocates named return variables initialized to their zero values. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import (
"errors"
"fmt"
)
// Function returning 3 simultaneous values: (processedCount, utilizationRatio, error)
func BalanceClusterLoad(activeJobs int, workerCapacity int) (int, float64, error) {
if workerCapacity <= 0 {
return 0, 0.0, errors.New("workerCapacity must be greater than zero")
}
ratio := float64(activeJobs) / float64(workerCapacity)
processed := activeJobs
if activeJobs > workerCapacity {
processed = workerCapacity // Truncated to maximum throughput
}
return processed, ratio, nil // nil error represents successful execution
}
// Named return values pattern
func ComputeBounds(values []int) (min int, max int) {
if len(values) == 0 {
return 0, 0
}
min, max = values[0], values[0]
for _, v := range values {
if v < min {
min = v
}
if v > max {
max = v
}
}
return min, max // Explicit return of named variables
}
func main() {
fmt.Println("=== Go Multiple Return Values Pipeline ===")
// 1. Unpacking multiple return values on success
processed, ratio, err := BalanceClusterLoad(85, 100)
if err != nil {
fmt.Printf("[ERROR] Dispatch failed: %v\n", err)
} else {
fmt.Printf("Cluster Dispatched: %d jobs | Load Ratio: %.2f | Status: OK\n", processed, ratio)
}
// 2. Unpacking error state and discarding unneeded results
_, _, err = BalanceClusterLoad(50, 0)
if err != nil {
fmt.Printf("Caught Expected Error: %v\n", err)
}
// 3. Named return values invocation
sampleMetrics := []int{42, 18, 95, 7, 63}
minimum, maximum := ComputeBounds(sampleMetrics)
fmt.Printf("Computed Boundaries: Min=%d, Max=%d\n", minimum, maximum)
}Expected Output:
=== Go Multiple Return Values Pipeline === Cluster Dispatched: 85 jobs | Load Ratio: 0.85 | Status: OK Caught Expected Error: workerCapacity must be greater than zero Computed Boundaries: Min=7, Max=95
How It Works: Step-by-Step
- Lines 9-19: Defines BalanceClusterLoad returning (int, float64, error) simultaneously.
- Lines 22-33: Demonstrates named return parameters (min int, max int) initialized to 0.
- Lines 39-44: Unpacks all three return values and inspects err != nil before using results.
- Lines 47-50: Uses blank identifier _ to ignore numeric returns and isolate the error.
Key Concepts
- Go functions can return multiple values, eliminating the need to wrap outputs in ad-hoc classes or structs.
- The standard Go idiom is to place the error value as the final return parameter (T, error).
- Callers must always check if err != nil before consuming the primary return value.
- Named return variables are pre-declared at the top of the function and initialized to their zero values.
Common Mistake: Ignoring the returned error using the blank identifier _
Discarding the error value with _, _, _ = fn() silently swallows runtime failures, causing downstream nil pointer dereferences or data corruption.
❌ Incorrect
res, _ := BalanceClusterLoad(10, 0) // Dangerous: ignores error!
✅ Correct
res, err := BalanceClusterLoad(10, 0)
if err != nil { return err } // Proper validationRelated Go Tutorials & Compiler
Go Pointers and Pass-by-Reference (* and &)
Master memory pointers in Go: address-of (&), dereference (*), and mutating function arguments.
Go Methods and Receiver Functions: OOP Without Classes
Implement OOP methods in Go using value and pointer receivers on structs.
Go Error Handling: if err != nil, fmt.Errorf, and errors.Is
Master idiomatic Go error handling with explicit error checking and error wrapping (%w).
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.