Rust中的"type()"是什么类型的?

pgr*_*pgr 8 rust

作为学习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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在构建时,我得到这个我不明白的错误.什么()类型?变量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`
Run Code Online (Sandbox Code Playgroud)

Mat*_* M. 11

()单位类型单一类型:它有一个单独的值,也表示().

我个人将其视为具有0个元素的元组.

在C或C++使用void(没有值)来指示函数的返回类型的情况下,Rust不会返回任何有趣的东西,()而是使用Rust .这对元编程来说要好得多,因为()接受值的常规类型,可以变异,借用等等......


关于您的特定代码示例:

if key == arr[mid] {
    mid as usize
}
Run Code Online (Sandbox Code Playgroud)

是一个类型的表达式()(因为没有else分支)但是你试图让if块评估mid as usize哪个具有类型,usize因此编译器注意到不匹配.

你想在return这里使用:

if key == arr[mid] {
    return mid as usize;
}
Run Code Online (Sandbox Code Playgroud)


Aur*_*001 9

()是单位类型,类似于void其他语言的返回类型.

你在这里得到它:

if key == arr[mid] {
    mid as usize
}
Run Code Online (Sandbox Code Playgroud)

Rust期望if表达式返回(),但是你要返回usize该表达式.因为Rust中的所有内容实际上都是一个表达式,所以通常可以隐式返回,就像你在这里尝试一样,但在这种特定情况下你不能,因为if表达式不是表达式中的唯一while表达式.您可以通过return mid as usize;改为使用来解决当前问题.