Gatonito
Gatonito

Reputation: 2174

How to use `Option<MyStruct>` on format?

I'm trying to use an Option of a Method on format!

/// Converts a method into a `&str`.
impl<'a> From<&'a Method> for &'a str {
    fn from(v: &'a Method) -> Self {
        match v {
            Method::Describe => "DESCRIBE",
            Method::GetParameter => "GET_PARAMETER",
            Method::Options => "OPTIONS",
            Method::Pause => "PAUSE",
            Method::Play => "PLAY",
            Method::PlayNotify => "PLAY_NOTIFY",
            Method::Redirect => "REDIRECT",
            Method::Setup => "SETUP",
            Method::SetParameter => "SET_PARAMETER",
            Method::Teardown => "TEARDOWN",
            Method::Extension(ref v) => v,
        }
    }
}

How do I use a Option<Method> in format!? I don't want to use unwrap, I want it to be empty in case there's no Method

I guess it's something like this:

let method = `Some(Method::Describe);
let method = match method {
    Some(method) => method.something,
    None => ""
};

Upvotes: 0

Views: 58

Answers (1)

chills42
chills42

Reputation: 14523

I believe in this case you can use map_or_else

So what you have would looks something like this?

let method = Some(Method::Describe);
let method = method.map_or_else(|| String::default(), |m| m.something);

Upvotes: 1

Related Questions