liveBook · Manning

Function type

As explained in 100 Go Mistakes and How to Avoid Them

A function type is a Go type whose values are functions with a specified parameter and result signature.

Calling time.Now() directly makes time-dependent tests brittle: execution timing affects which events survive. A function type turns that clock lookup into an injectable dependency. The named type now represents func() time.Time, while production code supplies time.Now and tests supply a deterministic function. section 11.6

Replace the real clock in tests

Define the dependency as type now func() time.Time and store it on Cache. NewCache initializes now with time.Now; a test can inject a function returning a fixed timestamp before calling TrimOlderThan.

Choose the dependency boundary according to what the code needs:

  • Prefer a function type when only one operation, such as retrieving the current time, is required. section 11.6
  • Avoid replacing the dependency with a mutable global variable, which prevents isolated parallel tests. section 11.6

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines a named function type, wires production and test implementations, and contrasts function injection with global state and explicit arguments.
Examples
Uses Cache, time.Now, TrimOlderThan, fixed timestamps, and a fake func() time.Time implementation.
What you can do after
Build deterministic time-dependent tests by injecting a function that returns a controlled timestamp.
How it connects
Connects function types with dependency injection, unit testing, deterministic tests, interfaces, global variables, and time APIs.

Also explained in

Compare how 4 books explain function type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.