Rust programming video tutorial (Advanced) – 005_ 3 values in closure capture environment

Time:2021-11-11

Video address

Headline address:https://www.ixigua.com/i677586170644791348…
Station B address:https://www.bilibili.com/video/av81202308/

Explanation content

1. Closures capture values in the environment

fn main() {
    let x = 4;
    let equal_ to_ x = |z| z == x; // Capture values in the environment
    let y = 4;
    assert!(equal_to_x(y));
}

Closures can capture their environment in three ways. They correspond to the three methods of obtaining parameters of functions: obtaining ownership, variable borrowing and immutable borrowing.

The three methods of capturing values are encoded as the following three FN traits:
(1) Fnonce consumes variables captured from the surrounding scope, and the scope around the closure is called its environment. In order to consume the captured variables, the closure must take ownership of them and move them into the closure when the closure is defined. The once part of its name represents that a closure cannot acquire ownership of the same variable more than once.
(2) Fnmut gets a variable borrowing value, so its environment can be changed.
(3) FN gets immutable borrowing values from its environment.
When creating a closure, trust infers how we want to reference the environment based on how it uses variables in the environment. Since all closures can be called at least once, all closures implement fnonce. Closures that do not move the ownership of captured variables to closures also implement fnmut, while closures that do not need variable access to captured variables implement FN.

2. If you want to force closure to take ownership of variables in the environment, you can use the move keyword before the parameter list. Examples are as follows:

fn main() {
    let x = vec![1, 2, 3];
    let equal_ to_ x = move |z| z == x; // Move to closure
    println! ("x ===== {}", x); // An error is reported here because X has been moved to the closure
    let y = vec![1, 2, 3];
    assert!(equal_to_x(y));
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed