Go Fundamentals

Lesson 4 of 8

Functions and Multiple Return Values

Go functions are straightforward, with one distinctive feature that shapes idiomatic Go code more than almost anything else: they can return multiple values.

func add(a int, b int) int {
    return a + b
}

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide %v by zero", a)
    }
    return a / b, nil
}
result, err := divide(10, 0)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Result:", result)
}

Why Go does errors this way

Go deliberately has no exceptions for ordinary error handling. Instead, any function that can fail returns an error as its last value, nil means success. The caller checks if err != nil immediately after every call that could fail, this is more verbose than a try/catch, but it makes every possible failure point visible directly in the code, nothing can silently fail three function calls away.

Named returns

func minMax(nums []int) (min, max int) {
    min, max = nums[0], nums[0]
    for _, n := range nums {
        if n < min { min = n }
        if n > max { max = n }
    }
    return // "naked" return, sends back the current values of min and max
}

Naming return values documents intent directly in the function signature, and lets a bare return send back whatever they currently hold.

📝 Functions Quiz

Passing score: 70%
  1. 1.How does idiomatic Go typically signal that a function call failed?

  2. 2.A nil error return value conventionally means the function call succeeded.

  3. 3.A Go function can return more than one value at once, commonly a result and an ____.