Fn closures

Closures that access variables only for read access implement the Fn trait. Any value they access are as reference types (&T). This is the default mode of borrowing the closures assumes. Consider the following code:

// fn_closure.rs

fn main() {
let a = String::from("Hey!");
let fn_closure = || {
println!("Closure says: {}", a);
};
fn_closure();
println!("Main says: {}", a);
}

We get the following output upon compilation:

Closure says: Hey!
Main says: Hey!

The a variable was still accessible even after invoking the closure as the closure used a by reference.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset