问题在评论中。 Expensive
是未实现Copy
的结构,或者复制太昂贵。
更新:用用户枚举Option
替换Internal
。
enum Internal {
Type1(Expensive),
Type2(String),
Empty,
}
struct Foo {
value: Internal,
}
impl Foo {
fn exec(&mut self) -> Result<Expensive, String> {
if let Internal::Type1(_) = &self.value {
let value = std::mem::take(&mut self.value);
// QUESTION: how do I avoid this pattern matching since we know the value must be Internal::Type1
return match value {
Internal::Type1(e) => Result::Ok(e),
_ => Result::Err(String::from("Impossible")),
};
}
// Some other logic that will use self.value
}
}
最佳答案
您可以利用 Option::take
使代码更短:
if let Option::Some(value) = self.value.take() {
return Ok(value);
}
关于enums - Rust:在没有其他模式匹配的情况下获得枚举值的所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64761331/