Search code examples
rustmatchbinary-searchcode-duplicationresulttype

What is the idiomatic way to handle code duplication in match bindings for Result?


I'll give some context here. The closure foo takes in a character and inserts it into a sorted vector. foo uses binary_search_by_key to insert the character into the vector at the correct index.

What would be a more idiomatic way of doing:

match myvec.binary_search_by_key(<--snip-->) {
    Ok(idx) => idx,
    Err(idx) => idx,
}

?


Solution

  • Not sure if more idiomatic, but you could use unwrap_or_else:

    let idx = myvec.binary_search_by_key(<--snip-->).unwrap_or_else(|idx| idx);