4 ms·
fn binary_search<T: Ord>(mut array: &[T], key: T) -> Option<T> A more useful signature would have been fn binary_search<T: Ord>(mut array: &[T], key: T) ->
by tsimionescu 6y ago
fn binary_search<T: Ord>(mut array: &[T], key: T) -> Option<T>
A more useful signature would have been
fn binary_search<T: Ord>(mut array: &[T], key: T) -> Option<usize>
And then returning `Some(middle)` on the Equal match. Returning the value you were given or None would be better expressed as returning True/False to avoid the unnecessary copy.
- justinpombrio 6y ago> A more useful signature would have been [returning the index]. Good point! And if you're doing that, there's no reason to use slices. So I guess the only thing to learn from my code... is that slices do useful bookkeeping for problems similar to this, in the case that you don't care about the indices? > Returning the value you were given or None would be better expressed as returning True/False to avoid the unnecessary copy. Just because two values are equal, doesn't mean they're the same. Though my function signature was wonky, regardless.