问题描述
假设我有一个包含 Option<Resource>
的结构,其中 Resource
是我需要使用的某种类型,需要分配外部资源(在实际情况下为 GPU 内存),因此可能会失败。在方法中,如果尚未完成分配,我想尝试分配,但如果失败则传播或处理错误。
如果不是失败案例,Option::get_or_insert_with
就完美了。实际上,我想到的最简洁的解决方案是 unwrap()
,它看起来很不雅观,因为它看起来像是潜在的恐慌:
struct Container {
resource: Option<Resource>,...
}
impl Container {
...
fn activate(&mut self) -> Result<(),Error> {
if self.resource.is_none() {
self.resource = Some(Resource::new()?);
}
let resource: &mut Resource = self.resource.as_mut().unwrap();
// ... now do things with `resource` ...
Ok(())
}
...
}
有没有比这更简单的初始化 Option
的方法?需要明确的是,我不是唯一在寻找避免unwrap()
,而是要避免整体可读性。如果替代方案更加复杂和间接,我宁愿坚持这个。
完整示例代码 (on Rust Playground):
#[derive(Debug)]
struct Resource {}
#[derive(Debug)]
struct Error;
impl Resource {
fn new() -> Result<Self,Error> {
Ok(Resource {})
}
fn write(&mut self) {}
}
#[derive(Debug)]
struct Container {
resource: Option<Resource>,}
impl Container {
fn new() -> Self {
Self { resource: None }
}
fn activate(&mut self) -> Result<(),Error> {
if self.resource.is_none() {
self.resource = Some(Resource::new()?);
}
self.resource.as_mut().unwrap().write();
Ok(())
}
}
fn main() {
Container::new().activate();
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)