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 or singleton type: it has a single value, also denoted ()
.
I personally view it as a tuple with 0 elements.
Where C or C++ would use void
(which has no value) to indicate the return type of a function which returns nothing interesting, Rust uses ()
instead. This is much nicer to meta-programming, as ()
is a regular type which accepts values, can be mutated, borrowed, etc...
Regarding your specific code sample:
if key == arr[mid] {
mid as usize
}
is an expression of type ()
(because there is no else
branch) yet you are attempting to have the if
block evaluate to mid as usize
which has the type usize
thus the compiler notices the mismatch.
You want to use a return
here:
if key == arr[mid] {
return mid as usize;
}