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
"Pure" closures are just functions
https://play.rust-lang.org/?gist=bc4d677696ac6afa887a25c425e7114d
Closures that capture the environment are each their own type, but all obey some corresponding
Fn
traithttps://play.rust-lang.org/?gist=da8d32b5212edf47427787743e271b63
However, be careful about generics vs trait objects
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 traitFn
&mut self
: Closure is of traitFnMut
self
: Closure is of traitFnOnce
Also, environment values themselves can be:
By reference (normal case)
Owned (
move
closure)
Generics vs Trait Objects
Each closure has a different size, so can't just handle them willy-nilly
Each closure is of a different type, so generics don't work so well with them
This leaves the joy of trait objects
https://play.rust-lang.org/?gist=be0c56a6315761ae8c1eac46401ce0d1
Final Notes
Values implementing
Copy
confuse everybodyThis stuff is hard; get some experience with it right now