Unwrap_or ref to default()

Hi,

While working on Rust code I'm often doing this:

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.

Why not something like this?

let value = construct_optionnal_value().unwrap_or_default();
call_fn(&optional_value);
1 Like

True, that's because I oversimplified my example:

let optional_value: Option<MyType> = construct_optionnal_value();
let default_value = MyField::default();
call_fn(optional_value.as_ref().map(|v| &v.field).unwrap_or(&default_value));

Ah ok. Things got less simple in this case.

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);
1 Like

… I didn't know that we can put a let without a value like this :open_mouth: Thanks!

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);
1 Like