The `?` operator and a `Carrier` trait

I was about to post here about how I found the perspective baffling that Result should be only for errors, or that binary_search should return anything other than Result<usize,usize>, citing the plethora of useful methods you lose access to when you write some one-off type like enum BinarySearchResult.

But then I recalled something: The one time I used binary_search myself, I didn’t get to use any of those cool methods, because what I really needed was this:

fn insertion_index(vec: Vec<T>, x: &T) -> usize {
    match vec.binary_search(x) {
        Ok(i) -> i,
        Err(i) -> i,
    }
}

which is a functionality Result doesn’t have a method for, perhaps due to the common perception that Result<T,T> is absurd.

(that said, I would sooner expect to see -> (bool, usize) than -> ::std::slice::SomeEnumThatIsntInPrelude)

For reasoning on why I think ? definitely should support Option is this code I wrote. I had to write an otry! macro due to the heavy usage of Option chaining I was otherwise doing.

https://github.com/rust-lang/rust/pull/34492

Not to think to far into the future, in Autoclosures (via swift) I have an example of how one might generalize ? for any Monad.

1 Like

When there really is no possible error other than “not found”, I think Option has the right semantic for the return value.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.