The Analogy: The Contractor's Business Card
When a building manager needs a leaking pipe fixed, they do not learn plumbing. They open a drawer, pull out a card that says "plumber", and hand it to whoever is on site. The card is not the work and it is not the plumber — it is a way of referring to them that fits in an envelope. You can photocopy it, file it under "emergencies", post it to a colleague, or get one back when you ask the trade association who covers your postcode.
A Go function value is that card. f := divide puts the card in a variable; f(9, 2) calls the number on it. And crucially the card has a type, printed on the front: func(int, int) (int, error) names the trade and the paperwork. Only cards with that exact signature fit that exact slot, which is how the compiler stops you filing an electrician under plumbing. Two function types are the same type when their parameters and results match in order and type; the parameter names are documentation and nothing more.
"First-class" is the claim that these cards go everywhere any other value goes. You can store them in a slice or a map to build a dispatch table, pass them into a function as a callback or a comparator, return them from a function to build one on demand, and put them in a struct field. There is no Function object to construct and no reflection involved. A function value is just a value, and every place you have already put an int will take one.
Three of Go's choices here surprise newcomers. Functions can return several values, which is why error handling is a returned error rather than an exception. There is no overloading and there are no default arguments — one name means one signature, and the workarounds are variadic parameters or a config struct. And the zero value of any function type is nil, so an unassigned card is an empty slot; calling it panics, and nil is the only thing a function value can be compared against.
Syntax or Core Structure
Multiple results, named results, variadics, a named function type, and functions as parameters and return values.
package main
import (
"errors"
"fmt"
"strings"
)
// Two results: the value and the paperwork.
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("divide by zero")
}
return a / b, nil
}
// Named results document the signature and permit a bare return.
func minMax(nums ...int) (lo, hi int, ok bool) {
if len(nums) == 0 {
return // yields 0, 0, false
}
lo, hi, ok = nums[0], nums[0], true
for _, n := range nums[1:] {
if n < lo {
lo = n
}
if n > hi {
hi = n
}
}
return
}
// A function type is a type, and can be named like any other.
type transform func(string) string
func applyAll(s string, steps ...transform) string {
for _, step := range steps {
s = step(s)
}
return s
}
// Returning a function: the caller gets a card built to order.
func prefixer(p string) transform {
return func(s string) string { return p + s }
}
func main() {
if q, err := divide(9, 2); err == nil {
fmt.Println("9/2 =", q)
}
if _, err := divide(1, 0); err != nil {
fmt.Println("error:", err)
}
lo, hi, ok := minMax(4, 9, 2, 7)
fmt.Println("lo:", lo, "hi:", hi, "ok:", ok)
_, _, ok = minMax()
fmt.Println("empty ok:", ok)
nums := []int{5, 1, 8}
lo, hi, _ = minMax(nums...) // spread an existing slice
fmt.Println("spread:", lo, hi)
// Library functions fit the transform slot: identical signature.
fmt.Println(applyAll(" Go ", strings.TrimSpace, strings.ToUpper, prefixer("lang: ")))
var nilFn transform
fmt.Println("nil func:", nilFn == nil)
}
Output:
9/2 = 4
error: divide by zero
lo: 2 hi: 9 ok: true
empty ok: false
spread: 1 8
lang: GO
nil func: true
Note what applyAll accepted: two functions from the standard library and one built at run time by prefixer. None of them knows about transform, and none of them needs to — assignability between a named function type and an identical unnamed one is automatic. That is the whole trick behind Go's callback-heavy standard library.
Technical Depth: Signatures, Results, Variadics and Method Values
Signature identity
| Declaration | Type |
|---|---|
func f(a, b int) string | func(int, int) string |
func g(x, y int) string | The same type. Parameter names are not part of it. |
func h(a int, b int) (s string) | Still the same type. Result names are not part of it either. |
type transform func(string) string | A defined type whose underlying type is func(string) string; the two are mutually assignable. |
func k(a ...int) | func(...int) — distinct from func([]int), despite the parameter being a slice inside. |
Results
The (value, error) pair is the language's central convention: the value is only meaningful when the error is nil, and the comma-ok form (v, ok := m[k]) is the same idea when there is nothing to explain. Go allows any number of results, but past three the call site becomes unreadable and a struct is better.
Named results do three jobs. They document what a bare return yields, they let defer inspect or replace the result before the caller sees it — the next-but-one lesson's central trick — and they pre-declare the variables so the body can assign them. Their cost is that a naked return twenty lines below the signature is hard to read, so name the results and still return them explicitly in anything longer than a few lines.
Parameters are always copies
Go passes every argument by value, with no exceptions. What varies is what the value is: an int copies the number, a struct copies every field, a slice copies the three-word header (so the callee sees the same backing array), and a map or channel copies a handle to shared state. "Pass by reference" is not a thing Go has; passing a pointer is passing a copy of an address, which achieves the same end explicitly.
Variadics
func log(level string, args ...any) {} // args is a []any inside
log("info") // args is nil, not empty
log("info", 1, "two") // args is []any{1, "two"}
vals := []any{1, "two"}
log("info", vals...) // no copy: args IS vals
The last line matters. Spreading a slice hands the callee the same backing array, so a callee that appends may overwrite the caller's data. Variadic parameters must come last, there can be only one, and a variadic function cannot be called with a mix of spread and individual arguments.
No overloading, no default arguments
One name, one signature. The alternatives, in rough order of preference: a second function with a clearer name (ParseInt and ParseUint), a config struct passed by value, or the functional options pattern that module 12 builds. What you should not do is invent DoThingWithFlagsAndTimeout.
What a function value actually is
A function value is a pointer to a code entry point, plus — for a closure — a pointer to its captured environment. Consequences worth knowing: function values are not comparable to each other (f == g does not compile; only f == nil does), they can be nil and calling a nil one panics, and an indirect call through a variable cannot be inlined by the compiler, which is the one real performance difference against calling a named function directly.
Method values and method expressions
| Form | Type | Meaning |
|---|---|---|
sb.WriteString | func(string) (int, error) | Method value: the receiver is captured now and baked in. |
(*strings.Builder).WriteString | func(*strings.Builder, string) (int, error) | Method expression: the receiver becomes the first parameter. |
Method values are how you pass a method where a plain function is expected, and they are the reason http.HandlerFunc(myFunc) works: a defined function type can itself have methods, so HandlerFunc satisfies the Handler interface by calling itself. Module 5 returns to this.
Recursion and mutual recursion
Recursion is ordinary. Go does not guarantee tail-call optimisation, so depth costs stack — though goroutine stacks start small and grow, so the practical limit is high. A recursive closure needs its variable declared before it is assigned, because the body has to refer to a name that already exists:
var walk func(n int) int
walk = func(n int) int {
if n <= 1 {
return n
}
return n + walk(n-1)
}
Real World Example: A Validation Schema Built From Function Values
A dispatch table of rules, a combinator that composes them, and the same signature at every level.
package main
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
)
type rule func(string) error
func required(v string) error {
if strings.TrimSpace(v) == "" {
return errors.New("must not be empty")
}
return nil
}
func numeric(v string) error {
if _, err := strconv.Atoi(v); err != nil {
return errors.New("must be a whole number")
}
return nil
}
// A rule built to order.
func maxLen(n int) rule {
return func(v string) error {
if len(v) > n {
return fmt.Errorf("must be at most %d characters", n)
}
return nil
}
}
// A combinator: rules in, one rule out, same type throughout.
func all(rules ...rule) rule {
return func(v string) error {
for _, r := range rules {
if err := r(v); err != nil {
return err
}
}
return nil
}
}
var schema = map[string]rule{
"id": all(required, numeric),
"name": all(required, maxLen(8)),
"notes": maxLen(12),
}
func validate(row map[string]string) []string {
fields := make([]string, 0, len(schema))
for f := range schema {
fields = append(fields, f)
}
sort.Strings(fields) // map order is random; the report must not be
var problems []string
for _, f := range fields {
if err := schema[f](row[f]); err != nil {
problems = append(problems, fmt.Sprintf("%s: %v", f, err))
}
}
return problems
}
func main() {
rows := []map[string]string{
{"id": "1", "name": "ada", "notes": "first"},
{"id": "x", "name": "", "notes": "far too long here"},
{"id": "3", "name": "grace hopper", "notes": ""},
}
for i, row := range rows {
problems := validate(row)
if len(problems) == 0 {
fmt.Printf("row %d ok\n", i)
continue
}
fmt.Printf("row %d %d problem(s)\n", i, len(problems))
for _, p := range problems {
fmt.Println(" ", p)
}
}
// A method value: the receiver is already bound inside the card.
var sb strings.Builder
write := sb.WriteString
write("method")
write(" values")
fmt.Println(sb.String())
}
Output:
row 0 ok
row 1 3 problem(s)
id: must be a whole number
name: must not be empty
notes: must be at most 12 characters
row 2 1 problem(s)
name: must be at most 8 characters
method values
schema is a dispatch table: a map whose values are function cards. Adding a field is adding a map entry, not editing a switch that three other functions also have to know about, and the schema can be assembled at run time from a config file just as easily as written by hand. Naming the type rule costs one line and makes every signature in the file shorter; map[string]func(string) error would compile identically and read considerably worse.
all is the piece that makes the design scale. It takes rules and returns a rule, so its output is indistinguishable from its inputs and can be nested to any depth — all(required, all(numeric, maxLen(4))) is valid and means what it looks like. This closure-returning-a-closure shape is exactly how HTTP middleware chains and sort comparators are built; maxLen captures its n for the lifetime of the returned function, and the next lesson is about what that capture really implies.
The two error strategies here are deliberate and different. Within a field, all fails fast: the first broken rule wins, because telling a user their ID is both non-numeric and too long rarely helps. Across fields, validate collects everything, because a form should report all its problems in one pass. When you want the collected version to be a single error rather than a slice of strings, errors.Join does it, and module 7 covers the inspection that makes joined errors useful.
The last three lines are a method value. sb.WriteString evaluates sb immediately and stores the receiver inside the function value, so write is a plain func(string) (int, error) that any callback slot will accept — no wrapper closure required. The method-expression form, (*strings.Builder).WriteString, leaves the receiver as the first parameter instead, which is what you want when the receiver varies per call. Both discard results freely here: Go permits ignoring every return value of a call used as a statement, and only go vet's specific checks (such as unchecked errors in some linters) will object.
Common Mistakes
- Calling a nil function value. The zero value of
func(...)is nil, so a struct field or map entry that was never set panics on call. Checkif f != nilat the boundary, or supply a no-op default when the struct is built.
- Expecting overloading. Two functions with the same name in one package is a compile error regardless of signature. Pick distinct names, or one function with a variadic option list.
- Ignoring an error result because the call reads fine.
divide(1, 0)compiles as a statement with both results discarded. Nothing warns you by default;errcheckand most CI linters exist for this.
- Mutating a spread variadic.
f(vals...)gives the callee the caller's backing array. If the callee appends within capacity, the caller's data changes. Copy inside the callee when it is going to modify what it received.
- Naked returns in long functions.
returnon line 60 of a function whose results were named on line 1 forces the reader to scroll. Name results for documentation and fordefer, then return the values explicitly anyway.
- Comparing function values.
if handler == fallbackdoes not compile. If you need to know which handler is installed, store a name or a small enum alongside it.
- Iterating a map of handlers and expecting a stable order.
schemaabove would report fields in a different order on every run without thesort.Strings. Any output derived from map iteration needs sorting.
- Assuming
func([]int)andfunc(...int)interchange. They are different types. A variadic function cannot be assigned to a slice-taking variable, and callingf(nums...)is required to pass a slice to the variadic one.
- Building a callback that silently swallows its error. A
func(string)callback with no error result forces every implementation to log-and-continue. Give callbacks anerrorresult unless you are certain failure is impossible.
- Deep recursion on untrusted input. A recursive parser on attacker-controlled nesting will exhaust the stack and crash the process, and a stack overflow cannot be recovered. Bound the depth explicitly.
- Forgetting that a returned function keeps its captured variables alive.
maxLen(n)is harmless, but a closure capturing a large buffer keeps that buffer out of the garbage collector's reach for as long as anything holds the function.
Best Practices
- Return
(value, error)and let the caller decide. A function that logs and returns nothing takes the decision away from every one of its callers.
- Name a function type when it appears more than twice.
type rule func(string) errorshortens every signature and gives the concept a place to hang documentation.
- Keep parameter lists short. Past three or four, pass a struct. It gives every argument a name at the call site and makes adding one a non-breaking change.
- Prefer a dispatch table to a growing switch when the cases are uniform, come from configuration, or need to be registered by other packages.
- Write combinators that return the same type they accept.
all(rules ...rule) rulecomposes;allBool(rules ...rule) booldoes not.
- Put the context or cancellation parameter first and the variadic options last.
func Do(ctx context.Context, id string, opts ...Option) erroris the shape readers expect.
- Give every callback an obvious failure path, whether that is an
errorresult or a documented contract about panics.
- Sort before you report. Any function that turns a map into output owes its caller a deterministic order.
Practice Exercises
- Write
func apply(nums []int, f func(int) int) []intreturning a new slice, then use it with a named function, a function literal, and a method value taken from a small struct with anAddmethod. Confirm all three fit the same parameter.
- Build a
map[string]func(float64, float64) (float64, error)calculator withadd,sub,mulanddiv, where onlydivcan fail. Look the operator up, report an error for an unknown one, and print the results in sorted operator order.
- Write a variadic
func sum(nums ...int) int, call it with no arguments, with three, and with a spread slice. Then write a second variadic function that appends to its ownnumsparameter and demonstrate whether the caller's slice changed. Explain the result.
- Implement
func retry(attempts int, f func() error) errorthat returns nil on the first success and the last error otherwise. Use it with a closure over a counter that fails twice and then succeeds, and print how many attempts were consumed.