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?

14.1. Assigning functions to variables

The weather station sensors provide an air temperature reading from 150–300° K. You have functions to convert Kelvin to other temperature units once you have the data, but unless you have a sensor attached to your computer (or Raspberry Pi), retrieving the data is a bit problematic.

14.2. Passing functions to other functions

14.3. Declaring function types

14.4. Closures and anonymous functions

Summary

sitemap