在写入枚举后获取对枚举中字段的引用的可靠方法

Infallible way to get reference to field in enum after writing to the enum

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

  1. 将值写入枚举
  2. Return 对刚刚写入的值的引用

这是我写的:

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.1.55)中看到 how it's implemented for Option:

    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(),编译器也应该能够将其作为死代码进行优化。