Lesson 14. First-class functions
After reading lesson 14, you’ll be able to
- Assign functions to variables
- Pass functions to functions
- Write functions that create functions
In Go you can assign functions to variables, pass functions to functions, and even write functions that return functions. Functions are first-class—they work in all the places that integers, strings, and other types work.
This lesson explores some potential uses of first-class functions as part of a theoretical Rover Environmental Monitoring Station (REMS) program that reads from (fake) temperature sensors.
Consider this
A recipe for tacos calls for salsa. You can either turn to page 93 of the cookbook to make homemade salsa or open a jar of salsa from the store.
First-class functions are like tacos that call for salsa. As code, the makeTacos function needs to call a function for the salsa, whether that be makeSalsa or openSalsa. The salsa functions could be used independently as well, but the tacos won’t be complete without salsa.
Other than recipes and temperature sensors, what’s another example of a function that can be customized with a function?