The issue here is that Rust evaluates the if/else if/else if
block as the return value because it lacks an else
clause, and statements which don't evaluate to any value have the type ()
. Incidentally, the code you've presented does exhaustively cover all possibilities (the item at the current index of the slice is either equal to, less than, or greater than the target), but the compiler doesn't know that unless you give it an else
clause at the end:
fn recursive_binary_search<T: Ord + Eq>(list: &[T], target: T) -> bool {
if list.len() < 1 {
return false;
}
let guess = list.len() / 2;
if target == list[guess] {
return true;
} else if list[guess] > target {
return recursive_binary_search(&list[0..guess], target);
} else {
return recursive_binary_search(&list[guess..list.len()], target);
}
}
PS: This function doesn't require mutable references, so I'd recommend using regular references as in my code above.
EDIT: For posterity, here's the same code w/o explicit returns:
fn recursive_binary_search<T: Ord>(list: &[T], target: T) -> bool {
if list.len() < 1 {
return false;
}
let guess = list.len() / 2;
if target == list[guess] {
true
} else if list[guess] > target {
recursive_binary_search(&list[0..guess], target)
} else {
recursive_binary_search(&list[guess..list.len()], target)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…