我想在不进行任何克隆的情况下,将旧变量的字段移动到新变量中并更新枚举变量:
enum X {
X1(String),
X2(String),
}
fn increment_x(x: &mut X) {
*x = match *x {
X::X1(s) => X::X2(s),
X::X2(s) => X::X1(s),
}
}
这不起作用是因为我们无法从&mut X
移动s
:
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:7:16
|
7 | *x = match *x {
| ^^
| |
| cannot move out of borrowed content
| help: consider removing the `*`: `x`
8 | X::X1(s) => X::X2(s),
| - data moved here
9 | X::X2(s) => X::X1(s),
| - ...and here
请不要建议像实现 enum X { X1, X2 }
和使用 struct S { variant: X, str: String }
等方式。这只是一个简单的例子,想象一下在各种变量中有很多其他字段,并且想将一个字段从一个变量移到另一个变量。
String
类型,你可以使用mem::replace
将空字符串替换到字段中,然后使用结果形成新的变量。只需要几个步骤。但是这仅适用于像空字符串这样具有廉价形式的类型。 - Sebastian Redlstd::mem::replace_with
,这应该有助于处理这种情况。 - Vlad Frolov