Understanding of Rust Option's unwrap_or_default method

Viewed 1992

The document of an_option.unwrap_or_default() is this:

pub fn unwrap_or_default(self) -> T

Returns the contained Some value or a default. Consumes the self argument then, if Some, returns the contained value, otherwise if None, returns the default value for that type.

I have the following testing program.

let a: Option<Option<i32>> = None;
println!("{:#?}", a.unwrap_or_default());

When I run it, it outputs None. But as I understand, a is an Option type and is None, so the return value should be the default value of Option<i32>. I'm not sure what is the default value of Option<i32>, maybe Some(0)? But I suppose None is not the default value of Option<i32>. Why the output is None? Thanks.

2 Answers

The accepted answer explains what's going on, the default value of the inner option being None.

As to why the default value of Option is None: if it defaulted to Some(T::default()), then Option would have to require T: Default for the option to be Default. Since the point of the Option type is to provide a None variant that doesn't require a T value at all, it's only natural for Option::default() to return that variant as the default value.

That maps perfectly to how Option is typically used. You want it to default to None because it means that the actual value hasn't yet been determined. If the default for Option<i32> were Some(0), you wouldn't be able to tell whether the option was at its default value or a 0 was already encountered and stored in it.

Related