如何在结构中强制转换为字段的枚举?

Rob*_*sen 2 enums struct casting rust

为什么施法会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();
}
Run Code Online (Sandbox Code Playgroud)

抛出此错误:

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
Run Code Online (Sandbox Code Playgroud)

lje*_*drz 5

我在官方消息来源中找不到任何关于它的信息,但似乎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`
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你是可变的借用self,所以它不能被消费(即移动); 如果你改变了签名bar(self)或由Foo通过导出可复制CloneCopy,它会工作.

  • 对于`Foo`,你肯定应该`#[derive(Copy,Clone)]`.因为它只能是纯整数,所以没有理由不复制它们. (2认同)