0
votes

My aim is to create a custom unwrap option function that works on any type which implements the default trait and in the case the type has no data (none) it returns the default for that type. Here is my attempt:

fn unwrap_option(data: Option<T>) -> T 

    where T: Default
{

    if(data.is_none()){
        return T::default();
    }
    else{
        return string.unwrap();
    }

}

But it doesn't work.

1
Are you trying to reinvent Option::unwrap_or_default?mcarton
"it doesn't work" → what doesn't work?mcarton
@mcarton That function is what I'm trying to do. I guess I'll read the source code to see how it was written. Thank you for your input.james pearson
That function uses a different(and arguably better) method than you are using, but your method would work fine if you added a type argument list (fn unwrap_option<T>(...) and fixed what I assume to be a typo, changing string.unwrap() to data.unwrap().Benjamin Lindley

1 Answers

1
votes

You're almost there!

/// Notice you were missing a generic parameter
fn unwrap_option /*->*/ <T> /*<-*/ (data: Option<T>) -> T 

    where T: Default
{

    if let Some(data) = data {
        data
    } else {
        T::default()
    }
}

This tries to get a value using an if let statement, and then returns the default if it is None. Another way to write this is the following:

fn unwrap_option<T: Default>(x: Option<T>) -> T {
    match x {                   // Have we got data?
        Some(x) => x,           // We do? Return it then
        None    => T::default(),// We don't? Get default then
    }
}

But, as mentioned in the comments using Option::unwrap_or_default is probably a better idea.