gpt4 book ai didi

rust - 为什么闭包在这里取得了 vector 的所有权?

转载 作者:行者123 更新时间:2023-11-29 07:58:46 24 4
gpt4 key购买 nike

rust 文档在 Closures 中有这个例子部分。

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

let takes_nums = || nums;

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

文档说

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

上面的代码导致了这个错误

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

文档说的

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.

我不明白为什么闭包不像文档中的示例那样只是借用 vector 的所有权

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.

最佳答案

答案在于闭包的签名:takes_num 是什么?返回?

它返回 nums , 其类型为 Vec<i32> .

要将某物的所有权授予某人,您必须首先拥有它,否则它不是您的。同样的规则适用于闭包。

关于rust - 为什么闭包在这里取得了 vector 的所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42534811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com