Search code examples
rust

Get value T from Result<T, T>


I have a function:

fn foo<i32>(x: i32) -> Result<i32, i32> {
    ...
}

I want to extract the value of the result into a variable, doesn't matter if it's Ok or Err. I could do that with:

let val = match foo(10) {
    Ok(i) => i,
    Err(i) => i,
}

Wondering if there's a "cleaner" or more "idiomatic" way of doing so, or if this is the best way to do so.

Note: Use case is for binary search, where I have a general function that returns Ok(i) with the index if a match is found, else it returns Err(i) with the index you'd insert the target to keep the array sorted. However, I don't want to expose this general function, and instead expose two variants binary_search and binary_search_insert_index. For the first, I just return i if Ok(i) else None. For the second, I just return the i no matter what.


Solution

  • You can use this pattern:

    fn unwrap_either<T>(result: Result<T, T>) -> T {
        result.unwrap_or_else(|e| e)
    }