作为学习Rust的一个简单练习,我决定实现一个简单的二进制搜索:
pub fn binary_search(arr: &[i32], key: i32) -> usize {
let min: usize = 0;
let max: usize = arr.len();
while max >= min {
let mid: usize = (max - min) / 2 as usize;
if key == arr[mid] {
mid as usize
}
if key < arr[mid] {
min = mid + 1;
continue;
}
max = mid - 1;
}
-1 as usize
}
#[cfg(test)]
mod tests {
use super::binary_search;
#[test]
fn binary_search_works() {
let arr: [i32; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
let index: usize = binary_search(&arr, 2);
assert_eq!(1, index);
}
}
在构建时,我得到了这个我不理解的错误.()
型是什么?变量mid
总是usize
,但即使是as
,我也会得到这个编译错误.
error: mismatched types [E0308]
mid as usize
^~~~~~~~~~~~
help: run `rustc --explain E0308` to see a detailed explanation
note: expected type `()`
note: found type `usize`