Understand the contract
Go functions can return multiple values. A common pair is a computed result and a signal explaining whether that result is usable. Use (value, bool) for a simple presence question and (value, error) when a failure needs explanation. Choose the form that matches the caller’s decision.
The first function returns the first integer in a slice and a presence flag. For an empty slice, zero is only a placeholder and false communicates absence. For []int{0}, the zero is real data and the flag is true. A single integer could not distinguish those cases.
Work through the example
The caller assigns both results with a short declaration and checks ok before using value. Keeping the check adjacent to the call prevents a placeholder from being mistaken for valid input. An early return makes the successful path continue without an extra level of nesting.
package main
import "fmt"
func first(values []int) (int, bool) {
if len(values) == 0 { return 0, false }
return values[0], true
}
func main() {
value, ok := first([]int{0})
if !ok { fmt.Println("empty"); return }
fmt.Println(value)
}Watch this boundary
Discarding a status result with _ is a deliberate decision, not a default convenience. If a collection may be empty, ignoring ok changes the meaning of zero. Named return parameters can document results, but long functions with bare returns can hide which values are actually being returned.
Practice with a changed input
Call first with nil, an empty non-nil slice and []int{0}. Write down the expected pair for each, then implement a last function with the same contract.
Lesson 23 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services