gpt4 book ai didi

rust - 如何解决 [E0382] : use of moved value in a for loop?

转载 作者:行者123 更新时间:2023-12-03 11:29:39 24 4
gpt4 key购买 nike

请帮我解决以下错误:

error[E0382]: use of moved value: `nd3`
--> src/main.rs:21:21
|
19 | Node::Y { nd: nd3, max: max } => {
| --- move occurs because `nd3` has type `std::boxed::Box<Node>`, which does not implement the `Copy` trait
20 | for m in 0..max - 1 {
21 | match recur(nd3) {
| ^^^ value moved here, in previous iteration of loop
代码如下。请不要介意代码看起来毫无意义,因为我简化了它:
enum Node {
X { x: usize },
Y { nd: Box<Node>, max: usize },
Z { Nd: Vec<Box<Node>> },
}

fn recur(nd: Box<Node>) -> Result<usize, ()> {
match *nd {
/// ...
Node::Y { nd: nd3, max: max } => {
for m in 0..max - 1 {
match recur(nd3) {
Ok(y) => return Ok(y),
_ => {}
}
}
return Ok(123);
}
_ => {}
}
return Ok(0);
}

最佳答案

如果您有一个拥有的值 ( nd ),并且您对其进行迭代,然后再次对其进行迭代,则会收到错误消息,因为它已移至循环的前一次迭代中。
一种解决方案是导出 Clone Node 的特征. Clone是显式复制对象的能力的共同特征:

#[derive(Clone)]
enum Node {
X { x: usize },
Y { nd: Box<Node>, max: usize },
Z { Nd: Vec<Box<Node>> },
}
现在您可以克隆 nd3当您再次递归调用该函数时:
Node::Y { nd: nd3, max: max } => {
for m in 0..max - 1 {
match recur(nd3.clone()) {
Ok(y) => return Ok(y),
_ => {}
}
}
return Ok(123);
}
现在,您不会将拥有的值传递给循环的下一次迭代。相反,您传递的是一个完全相同的副本。另一种解决方案是借用值(value)。但是,对于较小的对象,克隆更容易。

关于rust - 如何解决 [E0382] : use of moved value in a for loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64612490/

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