0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
berkes
  • 26,996
  • 27
  • 115
  • 206
  • 1
    As the Shepmaster's answer points: use map but as an alternative you can replace the `match` part with this: `Some(attr?.convert())` – Ömer Erden Jun 02 '20 at 13:39

1 Answers1

10

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366