Rust Some(x)没有像我期望的那样工作

时间:2016-06-08 13:11:05

标签: rust option-type

我尝试在Rust中实现二进制搜索(用于学习目的),并且我使用None来表示返回(Some(index)如果找不到,{{ 1}}如果找到了。)

这是我的代码:

fn bin_search(needle: i64,
              list: &[i64],
              from: Option<usize>,
              to: Option<usize>)
              -> Option<usize> {
    let left = from.unwrap_or(0);
    let right = to.unwrap_or(list.len());

    if left >= right {
        return None;
    } else {
        let mid = (left + right / 2) as usize;
        let guess = list[mid];

        if guess == needle {
            return Option::Some(mid);
        } else if guess > needle {
            return bin_search(needle, list, from, Some(mid - 1));
        } else if guess < needle {
            return bin_search(needle, list, Some(mid + 1), to);
        }
    }
}

错误信息:

src\main.rs:22:5: 30:6 error: mismatched types:
 expected `std::option::Option<usize>`,
    found `()`
(expected enum `std::option::Option`,
    found ()) [E0308]
src\main.rs:22     if guess == needle {
src\main.rs:23       return Some(mid);
src\main.rs:24     }
src\main.rs:25     else if guess > needle {
src\main.rs:26       return bin_search(needle, list, from, Some(mid - 1));
src\main.rs:27     }
               ...
src\main.rs:22:5: 30:6 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to previous error
error: Could not compile `binsearch`.

我怀疑错误是Some(mid),但我不知道为什么没有将其识别为正确的类型。它是Option<usize>,因为SomeOption,而mid正在投放到usize,除非我遗漏了某些内容。

0 个答案:

没有答案