As a simple exercise to learn Rust, I\'ve decided to implement a simple binary search:
pub fn binary_search(arr: &[i32], key: i32) -> usize {
let
() is the unit type, analogous to a void
return type in other languages.
You're getting it here:
if key == arr[mid] {
mid as usize
}
Rust is expecting that if expression to return ()
, but you're returning usize
for that expression. Since virtually everything in Rust is an expression, you can usually implicit return like you're trying to here, but in this specific case you can't because the if
expression is not the only expression in the while
expression. You could fix the immediate problem by using return mid as usize;
instead.