struct - 如何转换作为结构体内部字段的枚举?

标签 struct enums 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();
}

抛出此错误:

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/

相关文章:

C# - 将结构从一个对象传递到另一个对象

go - 如何在 Golang 中为嵌套数组结构初始化变量?

c# - 何时将枚举与 Entity Framework 一起使用?

swift - 您如何对具有您不关心的关联值的枚举案例进行简单的在线测试?

c++ - 为什么向下转换然后分配给 C++ 中的基类?

使用不同的键进行 JSON 解码

c - 指向结构的指针不递增

javascript - 根据条件 ng-change 更改 ng-model 字段的值

c++ - qobject_cast 是如何工作的?

C++ 类型转换