Higher-order functions and trait bounds that represent functions

A higher-order function is a function that takes another function, or a closure, as a parameter. In Rust, there are three somewhat unusual traits that allow us to specify a function or closure as a parameter's trait bound: Fn, FnOnce, and FnMut.

The differences between these traits are defined by what kind of variable access they permit:

  • FnOnce is the most widely applicable of these traits, because it has the fewest requirements on what types can implement it. An FnOnce only guarantees that it is safe to call it once. A function that consumes self is an example of a natural FnOnce, because having consumed self, it no longer has a self to be called on in future. Functions and ...

Get Rust Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.