0Pricing
Learn Rust Coding · Lesson

Fn, FnMut, FnOnce

Closure traits.

The Closure Traits

Every closure automatically implements one or more of three traits based on how it uses captured values:

  • Fn — borrows immutably.
  • FnMut — borrows mutably.
  • FnOnce — takes ownership, callable once.
fn main() {
    let x = 5;
    let show = || println!("x is {}", x); // implements Fn
    show();
    show();
}

Fn: Immutable Borrow

A closure that only reads captured values implements Fn. It can be called many times without changing anything.

fn main() {
    let greeting = String::from("Hi");
    let say = || println!("{}", greeting);
    say();
    say();
}

All lessons in this course

  1. Defining Functions
  2. Expressions and Statements
  3. Closures
  4. Fn, FnMut, FnOnce
← Back to Learn Rust Coding