Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a non-capturing closure be used after transferring ownership?

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?

like image 955
Some Name Avatar asked Sep 17 '25 03:09

Some Name


1 Answers

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:

  • Do all primitive types implement the Copy trait?
  • Why does "move" in Rust not actually move?
  • Can you clone a closure?
  • How do I clone a closure, so that their types are the same?
like image 118
Shepmaster Avatar answered Sep 19 '25 10:09

Shepmaster