let optional_value: Option<MyType> = construct_optionnal_value();
let default_value = MyType::default();
call_fn(optional_value.as_ref().unwrap_or(&default_value));
Creating default_value even if I don't need it is bothering me and I'm wondering if there's a better pattern?
I can't do unwrap_or_else(|| &MyType::default()) as ref to temp value is not possible.
let optional_value = construct_optional_value();
let default_field;
let field = match &optional_value {
Some(value) => &value.field,
None => {
default_field = MyField::default();
&default_field
}
};
call_fn(field);
You can use uninitialized values like that if your program can never access it in it's uninitialized state. Additionally, if it's immutable you can only assign to it once.
For example, this does not compile:
let value;
if true{
value = 42_u8;
}
dbg!(value);
...but these do:
let value;
if true{
value = 42_u8;
dbg!(value);
}
let value;
if true{
value = 42_u8;
} else{
unreachable!()
}
dbg!(value);