Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 147 ยท Functions

Functions as Values and Higher-Order Functions

Learn higher-order functions in Go - passing and returning functions, function types with methods, middleware-style wrappers, generic map, filter and reduce, and a preview of the options pattern.

You already know that Go functions are values and that closures remember the variables around them. This lesson puts both ideas to work. A higher-order function is a function that takes another function as an argument, returns a function, or both. Once you can write and read them, a lot of Go's standard library (sort.Slice, slices.SortFunc, http.HandlerFunc, strings.Map) stops looking magical.

You'll pass behavior into functions, return configured functions from factories, attach methods to function types (the trick behind http.HandlerFunc), wrap functions with middleware-style decorators, write generic Map, Filter and Reduce helpers as a preview of generics, and meet the functional options pattern.

Passing functions as arguments

Suppose you need to count the items in a slice that satisfy a rule. The loop is always the same; only the rule changes. Pass the rule in:

Go Passing a predicate to a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

isEven is a named function used as a value; the other two are literals, and the last one captures limit. Because countIf knows only the signature func(int) bool, it works with any rule you can express.

The standard library does this constantly. For example, slices.IndexFunc and strings.FieldsFunc take such functions, and so does sorting:

Go Sorting with a comparison function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The comparison function returns a negative number, zero or a positive number, so the same shape works for any ordering (Sorting goes deeper).

Returning functions

A function that returns another function acts as a factory. Each result is configured by the arguments of the factory and remembers them through a closure:

Go A function factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You can also compose functions: build a new function that runs several in sequence.

Go Composing functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

strings.TrimSpace and strings.ToLower fit directly because they have the signature func(string) string. The variadic parameter is covered in Variadic Functions.

Methods on function types

A function type is a defined type, and any defined type can have methods. That means a function can implement an interface. This is exactly how http.HandlerFunc lets an ordinary function serve as an http.Handler:

Go A function type that implements an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The method Greet just calls the function itself. Now one-off behaviors don't need a whole struct. See Interfaces for the full story of how types satisfy interfaces.

Decorators and middleware

A decorator takes a function and returns a new function with the same signature that adds behavior before and after the original. In web servers this is called middleware: logging, authentication, timing and retries are all written once and wrapped around many handlers.

Go Wrapping a function with logging and a call counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

chain wraps from the last middleware inward, so logging ends up outermost and sees the result of counting. The calls variable inside counting is created once per wrapped handler and kept alive by the closure. The real net/http package uses the same shape; you'll build one in Building an HTTP Server.

Map, Filter and Reduce

Most functional-style helpers need to work for any element type. Before Go 1.18 that was awkward. With generics (a quick preview here), you declare type parameters in square brackets:

Go Generic Map, Filter and Reduce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Map[T, U any] says "for any input type T and any output type U". Go infers both from the arguments, so you write Map(words, ...) without type arguments.

Go's standard library deliberately does not ship Map, Filter and Reduce for slices. Many Go programmers prefer a plain for loop, which is just as short, easier to debug and often faster. Helpers like these pay off when composing several steps or passing behavior into reusable code. Since Go 1.23, iterators offer a lazy way to chain such steps.

The functional options pattern

Constructors often have many optional settings. Instead of a constructor with a dozen parameters, accept a variadic list of option functions, each of which changes the object being built:

Go Functional options, a first look

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Callers write only what they care about, defaults live in one place, and new options can be added without breaking existing code. Constructors, Options and Builders explores this pattern in depth, including validation.

Things to watch for

  • A nil function value panics when called. Check if fn != nil for optional callbacks.
  • Functions can be compared only with nil, so they can't be map keys or compared with ==.
  • Closures passed to goroutines or stored for later keep their variables alive, which can prolong memory use.
  • Don't over-abstract: if only one caller exists, a direct call is clearer than a callback.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes a function higher-order?

    Higher-order functions treat functions as values: they accept them as arguments or return them.
  2. 2. Given type Op func(int) int and func (o Op) Twice(n int) int { return o(o(n)) }, what does Op(func(n int) int { return n + 3 }).Twice(1) return?

    The function adds 3 and Twice applies it two times: 1 + 3 + 3 = 7. Methods can be declared on function types.
  3. 3. In the chain example with chain(hello, logging, counting), which middleware is outermost?

    chain wraps from the last middleware inward, so the first one listed (logging) wraps everything else.
  4. 4. What happens if you call a function variable whose value is nil?

    Calling a nil function causes a nil pointer dereference panic. Check optional callbacks against nil first.
  5. 5. Which statement about comparing functions is true?

    The spec allows function values to be compared only to nil, so they cannot be map keys either.

Summary

  • A higher-order function takes functions as arguments or returns them; Go's first-class functions make this natural.
  • Passing a predicate or comparison function (as slices.SortFunc does) separates the loop from the rule.
  • Factories return closures configured by their arguments; compose chains several functions into one.
  • Methods on function types let plain functions satisfy interfaces, as with http.HandlerFunc.
  • Middleware and decorators wrap a function with the same signature to add logging, counting or timing in one place.
  • Generic Map, Filter and Reduce are easy to write but optional; a simple loop is often clearer.
  • The functional options pattern (opts ...Option) gives constructors flexible, backward-compatible configuration.
  • A nil function panics when called, and functions can be compared only with nil.

Next: Arrays begins the Collections chapter with Go's fixed-size sequences.