我试图更改枚举的命名属性,但出现此错误。
cannot move out of a mutable referencerustc(E0507)
parser.rs(323, 36): data moved here
parser.rs(323, 36): move occurs because `statements` has type `std::vec::Vec<std::boxed::Box<ast::ast::StatementType>>`, which does not implement the `Copy` trait
我看到我们可以使用match语句更改枚举的命名 Prop 。但是我不明白为什么会发生 move ,因为我是在借用枚举本身。这是代码:
match &mut block {
StatementType::Block { mut statements, .. } => {
statements = block_statements;
},
_ => panic!()
};
return block;
我也尝试过mem::swap,但是仍然是相同的错误:
match &mut block {
StatementType::Block { mut statements, .. } => {
// statements = block_statements;
std::mem::swap(&mut statements, &mut block_statements);
},
_ => panic!()
};
return block;
但执行此操作时:
std::mem::swap(&mut *statements, &mut *block_statements);
错误更改为:
the size for values of type `[std::boxed::Box<ast::ast::StatementType>]` cannot be known at compilation time
doesn't have a size known at compile-time
类型是:
statements
是Vec<Box<StatementType>>
的变量block_statements
是Vec<Box<StatementType>>
的另一个变量请不要说发生这种情况是因为语句的类型是Vector:提供了一个解决方案,因为我也可以读取错误消息。
最佳答案
您必须考虑statements
的类型是什么以及您希望它是什么类型。
使用您编写的代码,它的类型为Vec<_>
(对不起,我说过),但是由于match
通过引用捕获该块,因此无法按值获取内容,因此会出现错误。请注意,错误不在赋值中,而在匹配括号中:
error[E0507]: cannot move out of a mutable reference
--> src/main.rs:15:11
|
15 | match &mut block {
| ^^^^^^^^^^
16 | StatementType::Block { mut statements, .. } => {
| --------------
| |
| data moved here
| move occurs because `statements` has type `std::vec::Vec<std::boxed::Box<StatementType>>`, which does not implement the `Copy` trait
您当然希望
statement
的类型为&mut Vec<_>
。然后,您可以使用ref mut
捕获模式来获得它: match block {
StatementType::Block { ref mut statements, .. } => {
*statements = block_statements;
},
_ => panic!()
};
并请记住在分配时使用
*statement
,因为它现在是引用。当然,您也可以使用mem::swap
: std::mem::swap(statements, &mut block_statements);
但是请注意,您不需要
match &mut block
,但可以直接进行match block
。有一种叫做“匹配人体工程学”的东西,它使您可以与引用进行匹配,并省略
ref mut
捕获模式,这使您的代码更易于编写和理解: match &mut block {
StatementType::Block { statements, .. } => {
*statements = block_statements;
},
_ => panic!()
};
原始代码中的问题是,如果指定任何捕获模式,则将禁用匹配人体工程学。
关于vector - 带向量的Rust匹配可变枚举引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62360583/