Multiple Return Values
Multiple Return Values
Most languages let functions return one thing. Go lets you return as many as you want.
This is surprisingly useful. Think about a bank withdrawal: you need both the new balance AND whether the withdrawal was allowed. In other languages you'd return a special object or throw an exception. In Go, you just return both:
func withdraw(balance, amount int) (int, bool) {
if amount > balance {
return 0, false
}
return balance - amount, true
}The return type (int, bool) means this function hands back two values. No wrapper objects, no tuples. Just return two things separated by a comma.
Catching multiple returns
When you call a function that returns multiple values, you catch them all at once:
bandwidth, ok := withdraw(100, 30)If ok is true, you can trust remaining. If not, something failed.
This result, ok pattern shows up everywhere in Go. Even the standard library uses it. For example, strconv.Atoi converts a string to an integer and returns both the number and an error:
num, err := strconv.Atoi("42") // num = 42, err = nil
num, err := strconv.Atoi("nope") // num = 0, err = error
You'll see this pattern with map lookups, type assertions, and channel receives later on. Get comfortable with it now.
When to use this
Return multiple values when the caller needs to know both "what happened" and "did it work":
func divide(a, b float64) (float64, bool) {
if b == 0 {
return 0, false
}
return a / b, true
}
result, ok := divide(10, 3)Exercise: Book Seats
You're building a ticket booking system. Write a function called bookSeats(available, requested int) (int, bool) where available is how many seats are left and requested is how many someone wants to book.
If the booking is invalid, return 0, false. A booking is invalid when requested is zero, negative, or more than available.
If the booking is valid, subtract the requested seats from the available seats and return the result with true.
Examples:
| Call | Returns | Why |
|---|---|---|
bookSeats(50, 10) |
40, true |
40 seats left after booking 10 |
bookSeats(5, 20) |
0, false |
not enough seats |
bookSeats(10, 10) |
0, true |
booking the exact count is fine, 0 left |
bookSeats(10, 0) |
0, false |
zero is not a real booking |
bookSeats(10, -1) |
0, false |
negative is not a real booking |