gpt4 book ai didi

rust - 解构成对的 Box 时附带移动错误

转载 作者:行者123 更新时间:2023-11-29 07:50:44 26 4
gpt4 key购买 nike

下面两行:

let x = Box::new(("slefj".to_string(), "a".to_string()));
let (a, b) = *x;

产生错误:

error[E0382]: use of moved value: `x`
--> src/main.rs:3:13
|
3 | let (a, b) = *x;
| - ^ value used here after move
| |
| value moved here
|
= note: move occurs because `x.0` has type `std::string::String`, which does not implement the `Copy` trait

有趣的是,如果我对枚举类型执行此操作,我会得到一个稍微不同的错误:

enum Tree {
Nil,
Pair(Box<Tree>, Box<Tree>),
}

fn main() {
let x = Box::new(Tree::Nil);

match *x {
Tree::Pair(a, b) => Tree::Pair(a, b),
_ => Tree::Nil,
};
}

我得到错误:

error[E0382]: use of collaterally moved value: `(x:Tree::Pair).1`
--> src/main.rs:10:23
|
10 | Tree::Pair(a, b) => Tree::Pair(a, b),
| - ^ value used here after move
| |
| value moved here
|
= note: move occurs because `(x:Tree::Pair).0` has type `std::boxed::Box<Tree>`, which does not implement the `Copy` trait

为什么会发生这种情况,如何使用 let/match 轻松破坏结构并获得内部部件的所有权?我知道我可以首先取消引用并命名结构,但如果我深入结构进行模式匹配,那会变得非常冗长。

最佳答案

您偶然发现了一个 limitation on destructuring and boxes .幸运的是,解决这些问题很容易。您需要做的就是引入一个包含整个结构的新中间变量,并从中解构:

let x = Box::new(("slefj".to_string(), "a".to_string()));
let pair = *x;
let (a, b) = pair;

第二个例子:

let pair = *x;
match pair {
Tree::Pair(a, b) => Tree::Pair(a, b),
_ => Tree::Nil,
};

关于rust - 解构成对的 Box 时附带移动错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466809/

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