In a struct, I would like a method which sets an option to Some(my_object)
, then directly returns the inner reference of the object (&MyObject
, not Option<&MyObject>
).
In this case:
- Is it safe to use
Option::unwrap_unchecked()
? - Is it possible to not use a
unsafe
block, without loosing a tiny bit of runtime?
Minimal example:
#[derive(Debug, Default)]
struct Child {
// ...
}
#[derive(Debug, Default)]
struct Parent {
opt_child: Option<Child>,
// ...
}
impl Parent {
pub fn set_child(&mut self, child: Child) -> &Child {
self.opt_child = Some(child);
// SAFETY: we are 100% sure that self.opt_child is `Some`
unsafe {
self.opt_child.as_ref().unwrap_unchecked()
}
}
// ...
}
fn main() {
let mut parent = Parent::default();
let child = parent.set_child(Child::default());
println!("{:?}", child);
}