I'm trying to understand ownership in Rust and faced a misunderstanding related to transfer ownership. Consider the following code:
fn main() {
let closure = || 32;
foo(closure);
foo(closure); //perfectly fine
}
fn foo<F>(f: F) -> u32
where
F: Fn() -> u32,
{
f()
}
playground
I thought that the ownership should be transferred and the second call foo(closure)
should not be allowed.
Why does it work?
Your closure implements Copy
, so when you use it a second time, a copy is automatically made. Your code works for the same reason this does:
fn main() {
let v = 32;
foo(v);
foo(v);
}
fn foo(a: u32) -> u32 {
a
}
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With