Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding of Rust Option's unwrap_or_default method

Tags:

rust

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.

like image 728
Just a learner Avatar asked Dec 30 '22 14:12

Just a learner


1 Answers

a is an Option of Option, the default value of an Option is None. Check Option's Default trait implementation

like image 164
0x00A5 Avatar answered Feb 12 '23 17:02

0x00A5