How do I unwrap an arbitrary number of nested Option types?

后端 未结 3 1432
悲哀的现实
悲哀的现实 2020-12-06 11:42

I\'m trying to write a trait that will allow me to "unwrap" multiple nested Option>>> to a single Option

3条回答
  •  我在风中等你
    2020-12-06 12:15

    If you have many Options and you want to avoid chaining unwraps, you can use match:

    let val = Some(Some(Some(5)));
    let res = match val {
        Some(Some(Some(v))) => v,
        _ => 0, // panic or default
    };
    

提交回复
热议问题