作为学习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`

推荐答案

()是unit type,类似于其他语言中的void返回类型.

你现在明白了:

if key == arr[mid] {
    mid as usize
}

Rust期望if表达式返回(),但该表达式返回usize.因为Rust中几乎所有的东西都是一个表达式,你可以像这里try 的那样隐式返回,但是在这个特定的例子中你不能,因为if表达式不是while表达式中的only表达式.你可以用return mid as usize;来解决眼前的问题.

Rust相关问答推荐

捕获Rust因C++异常而产生panic

下载压缩文件

Rust TcpStream不能在读取后写入,但可以在不读取的情况下写入.为什么?

为什么`Vec i64`的和不知道是`Option i64`?

默认特征实现中的生命周期问题

如何向下转换到MyStruct并访问Arc Mutex MyStruct实现的方法?

使用关联类型重写时特征的实现冲突

允许 rust 迹 struct 条目具有多种类型

如何设置activx websocket actorless的消息大小限制?

如何轮询 Pin>?

如何将 struct 数组放置在另一个 struct 的末尾而不进行内存分段

可选包装枚举的反序列化

根据掩码将 simd 通道设置为 0 的惯用方法?

我可以禁用发布模式的开发依赖功能吗?

闭包返回类型的生命周期规范

返回迭代器的特征

是否可以预测堆栈溢出?

tokio async rust 的 yield 是什么意思?

在 Traits 函数中设置生命周期的问题

提取 struct 生成宏中字段出现的索引