简体   繁体   English

为什么闭包在这里取得了向量的所有权?

[英]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 但是,如果你的闭包需要它,Rust将取得所有权并改为移动环境

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. Vec拥有对其内容的所有权,因此,当我们在封闭中提及它时,我们必须拥有nums的所有权。 It's the same as if we'd passed nums to a function that took ownership of it. 这就像我们将nums传递给一个拥有它所有权的函数一样。

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. 这个闭包,plus_num,指的是其范围内的let绑定:num。 More specifically, it borrows the binding. 更具体地说,它借用了绑定。

The answer lies in the signature of the closure: what does takes_num return? 答案在于闭包的签名: takes_num返回什么?

It returns nums , whose type is Vec<i32> . 它返回nums ,其类型为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. 同样的规则适用于关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM