How to join the two Options<Vec<String>>

Viewed 139

case 1.

v1 = None
v2 = Some(vec[..])
result = Some(vec[..]) 

case 2.

v1 = Some(vec[..])
v2 = None
result = Some(vec[..]) 

case 3.

v1 = Some(vec[..])
v2 = Some(vec[..])
result = Some(vec[..])

case 4.

v1 = None
v2 = None
result = None

Is there a generalized way to implement this?

2 Answers

You can just use a match statement representing your cases:

let result = match (v1, v2) {
    (res@Some(_), None) => res,
    (None, res@Some(_)) => res,
    (Some(r1), Some(r2)) => Some(r1.into_iter().chain(r2).collect()),
    _ => None
};

Playground

You can take advantage of the fact that Options can be converted to Iterators and use Iterator::reduce:

v1.into_iter()
    .chain(v2.into_iter())
    .reduce(|mut v1, mut v2| {
        v1.append(&mut v2);
        v1
    })

Chaining the two Option iterators will give us an iterator that yields either 0 (if both v1 and v2 were None), 1 (if either v1 or v2 was None), or 2 (if both v1 and v2 were not None) vectors. Iterator::reduce will only "reduce" the iterator with the closure if there are 2 or more vectors in the iterator and otherwise will return the only vector, if any, in the iterator.

Rust Playground

Related