Closures

First-Class Functions

  • "First-class functions" are a thing. A thing is "first-class" if all the sensible operations of the language do indeed apply to it

  • In Rust, functions are first class

    • They have their own types

    • They can be passed as parameters, returned as results, stored in arrays, used as struct and enum fields, etc

    • They can be created in any block scope

    • References are available (indeed, a function essentially is a static reference)

    https://play.rust-lang.org/?gist=92076106592f0e34b7e7d7d7f25ea207

Closures

  • The problem with pure functions is that anything they compute has to be based on arguments

  • A closure is a function that is allowed to access its "environment": names that are statically in scope at the point of its declaration

  • Closures in Rust are mostly first-class, and can access parameters and locals like anything else

  • Syntax has wacky pipes and stuff; types are optional and inferred

Closures, Environments, Types

Closures As Environment Structs

  • Think of a closure as a code pointer and some anonymous struct holding the captured vars or refs to them and its implementation

  • Three kinds of implementation of the anonymous struct:

    • &self: Closure is of trait Fn

    • &mut self: Closure is of trait FnMut

    • self: Closure is of trait FnOnce

  • Also, environment values themselves can be:

    • By reference (normal case)

    • Owned (move closure)

Generics vs Trait Objects

Final Notes

  • Values implementing Copy confuse everybody

  • This stuff is hard; get some experience with it right now

Last modified: Tuesday, 8 May 2018, 6:04 PM