Slices, maps and strings · 3 MIN READ

A function is a value you can pass

Apply a func(int) int to every element of a slice.

The Tour's "Function values" page: functions are values. They can be arguments and results. The type includes the parameters and the result, so func(int) int and func(int) string are as different as int and string.

This is not a method and not a generic yet. It is the shape map and filter had in Go before type parameters, and it is still how most callbacks are written.

SEE THE IDEA

A signature is a contract you can pass

  1. 01

    Function value

    go
    func(int) bool

    Names the input and output types

  2. 02

    Parameter

    go
    keep func(int) bool

    Accepts any matching function

  3. 03

    Invocation

    go
    keep(value)

    Calls the supplied behavior

Named functions and closures can satisfy the same function type.

In practice

Pass a function when callers should choose one operation without defining a whole object. A closure can adapt an existing function or capture small configuration. Keep the signature narrow so it is easy to test; a function value may be nil, so establish whether nil is allowed.

Watch out

A nil function value can be compared to nil, but calling it panics. Other function values cannot be compared for equality.

Official reference ↗

Work through the exercise

go
package main

// Apply returns fn(v) for each v, in order.
func Apply(values []int, fn func(int) int) []int {
	return nil
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.