I just found out that the following code
fn create_fn_once() -> impl FnOnce(char) -> String {
let text = "text".to_string(); // not implement the `Copy` trait
let y = 1; // implement the `Copy` trait
|x| {
move_x(text); // ok
move_x(y); // error: `y` is borrowed here
x.to_string()
}
}
fn move_x<T: Sized>(x: T) {}
Fails with (playground)
error[E0373]: closure may outlive the current function, but it borrows `y`, which is owned by the current function
--> src/lib.rs:5:5
|
5 | |x| {
| ^^^ may outlive borrowed value `y`
6 | move_x(text); // ok
7 | move_x(y); // error: `y` is borrowed here
| - `y` is borrowed here
|
note: closure is returned here
--> src/lib.rs:5:5
|
5 | / |x| {
6 | | move_x(text); // ok
7 | | move_x(y); // error: `y` is borrowed here
8 | | x.to_string()
9 | | }
| |_____^
help: to force the closure to take ownership of `y` (and any other referenced variables), use the `move` keyword
|
5 | move |x| {
| ++++
I know move |x| { can fix it. But why is y borrowed?