पाठ 6 / 26

Functions, Multiple Returns and Closures

Return values and errors together.

Results plus an error

Functions can return several values, and the idiom is to return a result plus an error as the last value: callers check if err != nil. Unwanted values are discarded with _. Functions are values: you can pass them as arguments and return them, and closures capture variables from their surrounding scope, keeping them alive between calls.

Multiple returns, errors and a closure, run

I ran this with Go 1.27.1 (go run . in a module named demo, standard library only). divide returns a result and an error; the counter closure keeps its own n across calls; strconv.Atoi shows a standard library error for invalid input.

package main

import (
	"fmt"
	"strconv"
)

func divide(a, b float64) (float64, error) { // multiple return values
	if b == 0 {
		return 0, fmt.Errorf("divide %v by zero", a)
	}
	return a / b, nil
}

func counter() func() int { // a closure keeps its own state
	n := 0
	return func() int { n++; return n }
}

func main() {
	if q, err := divide(10, 4); err == nil {
		fmt.Println("10/4 =", q)
	}
	if _, err := divide(1, 0); err != nil {
		fmt.Println("error:", err)
	}
	next := counter()
	next(); next()
	fmt.Println("counter:", next())
	n, err := strconv.Atoi("42x")
	fmt.Println(n, err)
}

Output:

10/4 = 2.5
error: divide 1 by zero
counter: 3
0 strconv.Atoi: parsing "42x": invalid syntax

Return errors, do not ignore them

Discarding an error with _ should be a deliberate, commented choice, never a habit.

त्वरित जाँच: What is the idiomatic way for a Go function to report failure?

  • Exit the program
  • Throw an exception
  • Print to stderr and return 0
  • Return an error value as the last result
Answer

Return an error value as the last result — Errors are values.