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
- Defining Functions
- Expressions and Statements
- Closures
- Fn, FnMut, FnOnce