【问题标题】:Infallible way to get reference to field in enum after writing to the enum写入枚举后获取枚举字段引用的可靠方法
【发布时间】:2021-10-01 19:05:38
【问题描述】:

我正在编写一个需要做两件事的函数:

  1. 将值写入枚举
  2. 将引用返回到刚刚写入的值中

这是我写的:

enum State {
    Asleep,
    Awake { deeds: Vec<String> }
}

impl State {
    fn wake_up(&mut self) -> &mut Vec<String> {
        *self = Self::Awake { deeds: vec![] };
        match self {
            Self::Awake { deeds } => deeds,
            _ => unreachable!("WTF, how are we not awake!?")
        }
    }
}

unreachable! 的使用似乎不太优雅。有没有办法编写这个函数来避免处理(显然)不可能的情况?

【问题讨论】:

    标签: rust enums


    【解决方案1】:

    不,没有办法做到这一点。你可以在Option的标准库(Rust.1.55)中看到how it's implemented

        pub fn insert(&mut self, value: T) -> &mut T {
            *self = Some(value);
    
            match self {
                Some(v) => v,
                // SAFETY: the code above just filled the option
                None => unsafe { hint::unreachable_unchecked() },
            }
        }
    

    即使您使用unreachable!() 代替不安全的unreachable_unchecked(),编译器也应该能够将其优化为死代码。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多