FAQ - Help and questions

What are closures in Rust, and what do Fn, FnMut and FnOnce mean?

#closures#functions#traitspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A closure is an anonymous function that can use variables from the code around it. Rust picks how it captures them. Fn only reads them, FnMut changes them, and FnOnce takes ownership and can be called only once. Writing move before the closure forces it to take ownership of what it uses.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A closure is written |x| x + offset. Unlike a function, it may use offset from the surrounding code. The compiler works out the least it needs: a borrow to read, a mutable borrow to change, or ownership if the closure gives the value away. That gives each closure one of three traits:

TraitThe closureCan be called
Fnonly reads what it capturedany number of times
FnMutchanges what it capturedany number of times, needs mut
FnOncemoves a captured value outonce

Every Fn closure is also FnMut and FnOnce. A function that takes a closure asks for the weakest trait it can live with.

src/main.rsrust
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
    f(x)
}

fn call_once<F: FnOnce() -> String>(f: F) -> String {
    f()
}

fn main() {
    let offset = 10;
    let add_offset = |x| x + offset; // borrows `offset`: Fn
    println!("{}", apply(add_offset, 5));

    let mut count = 0;
    let mut tick = || {
        count += 1; // changes captured state: FnMut
        count
    };
    tick();
    tick();
    println!("ticks: {}", tick());

    let name = String::from("Ada");
    let consume = move || name; // gives the String away when called: FnOnce
    println!("{}", call_once(consume));
}
text
15
ticks: 3
Ada

How to use them#

  • Pass closures to iterator methods: .map(|x| x * 2), .filter(|x| *x > 3).
  • Ask for F: Fn(i32) -> i32 in your own function when the closure is called repeatedly and only reads; FnOnce when you call it a single time.
  • Use move || ... when the closure must outlive the current function, for example for thread::spawn. Without it the compiler stops with error E0373 ("closure may outlive the current function").

Common mistakes#

  • Forgetting mut on a closure variable: a closure that changes captured state must itself be declared let mut tick = || ....
  • Using the captured variable after a move closure took it. The closure now owns it.
    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet