为什么转换会将 self
移出借用的内容?
#[derive(Debug)]
enum Foo {
One = 1,
Two = 2,
}
struct Bar {
f: Foo,
}
impl Bar {
fn bar(&mut self) {
println!("{:?}", self.f); // "Two"
println!("{:?}", Foo::Two as u8); // "2"
println!("{:?}", self.f as u8); // error
}
}
fn main() {
Bar{f: Foo::Two}.bar();
}
抛出此错误:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:15:26
|
15 | println!("{:?}", self.f as u8); // error
| ^^^^ cannot move out of borrowed content
最佳答案
我在官方来源中找不到任何有关它的信息,但似乎 as
强制转换具有移动语义,即它们消耗强制转换对象;考虑这个简化的情况:
#[derive(Debug)]
enum Foo {
Foo1 = 1
}
fn main() {
let foo = Foo::Foo1;
let bar = foo as u8; // the cast moves foo
println!("{:?}", bar); // ok
println!("{:?}", foo); // error[E0382]: use of moved value: `foo`
}
在你的情况下,你不断地借用self
,所以它不能被消耗(即移动);如果您将签名更改为 bar(self)
或制造Foo
可通过派生 Clone
进行复制和Copy
,它会起作用。
关于struct - 如何转换作为结构体内部字段的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44289831/