SphericalCow
SphericalCow

Reputation: 365

Why does the closure take ownership of the vector here?

The rust documentation has this example in the Closures section.

let nums = vec![1, 2, 3];

let takes_nums = || nums;

println!("{:?}", nums);

The documentation says

If your closure requires it, however, Rust will take ownership and move the environment instead

And the above code results in this error

note: `nums` moved into closure environment here because it has type
  `[closure(()) -> collections::vec::Vec<i32>]`, which is non-copyable
let takes_nums = || nums;
                 ^~~~~~~

for which the docs say

Vec has ownership over its contents, and therefore, when we refer to it in our closure, we have to take ownership of nums. It’s the same as if we’d passed nums to a function that took ownership of it.

I don't understand why the closure doesn't just borrow the ownership of the vector as it does in this example from the documentation

let num = 5;
let plus_num = |x: i32| x + num;

assert_eq!(10, plus_num(5));

This closure, plus_num, refers to a let binding in its scope: num. More specifically, it borrows the binding.

Upvotes: 4

Views: 196

Answers (1)

Matthieu M.
Matthieu M.

Reputation: 299730

The answer lies in the signature of the closure: what does takes_num return?

It returns nums, whose type is Vec<i32>.

To give ownership of something to someone, you must first own it, otherwise it's not yours to give. The same rule applies to the closure.

Upvotes: 5

Related Questions