berkes
berkes

Reputation: 27543

How to convert the inner value in an Option?

I have an Option that contains some JSON. If it is Some, the inner JSON must be converted, but if it is None, it must remain None.

This is how I have this implemented currently:

struct One;
struct Other;

impl One {
    pub fn convert(&self) -> Other {
        Other {}
    }
}

fn example(attr: Option<One>) -> Option<Other> {
    match attr {
        Some(attr) => Some(attr.convert()),
        None => None,
    }
}

I'm new to Rust and don't fully get the intricacies of when to use match, if let or when to use the ? operator.

Is my implementation idiomatic Rust? It seems rather verbose to me, and looks like a pattern that will occur all over the place, so I can imagine this can be handled far more concise; is that so?

Upvotes: 1

Views: 4184

Answers (1)

Shepmaster
Shepmaster

Reputation: 430476

Use Option::map:

fn example_a(attr: Option<One>) -> Option<Other> {
    attr.map(|v| v.convert())
}

Since your function accepts a reference, you can also use Option::as_ref and then directly use the function inside of map instead of a closure:

fn example_b(attr: Option<One>) -> Option<Other> {
    attr.as_ref().map(One::convert)
}

See also:

Upvotes: 11

Related Questions