Go struct Callout functions are a powerful way to create highly configurable, easily testable, future proof structs.
This article should provide a brief overview of what struct Callout functions are, how they work, and when they might be useful. I recently answered a question
asking about this
,
and have been seeing this pattern in
many projects
including the
standard library
, and I really haven’t seen much written about it.
Struct Functions or “Callout” functions are powerful tool which provide a flexible configurable struct, and allow multiple implementations or functional options. Abstracting to a callout function can future proof a specific slice of functionality
by defining a clear relationship between a structure and a functional dependency. Once this functional dependency is defined it allows for different implementations to be provided. It is very similar to hiding a dependency behind an interface
but is a much smaller scope, as it is only a single function, instead of an interface with potentially multiple methods.
I have found go struct Callout functions to be a powerful way to introduce a
“seam”
into
a go struct in order to provide multiple implementations. Using a Callout function allows an alternative implementation to be provided during testing.
Consider a car struct that offers an outside temperature dashboard reading.
The outside temperature gauge is a common on dashboards the car “owns” but may not be directly dependent on the state of the car.
Configurable Implementations
The callout function above allows us to offer many different implementations without having to change anything but the
car
struct initialization. The following will walk through how a different Callout function implementation can
be configured for a variety of different contexts:
Production
Let’s imagine that we have a car company that offers a built in thermometer as a standard offering.
Now in the public initialization of car the thermometer can be configured and used to get the temp reading.