繁体   English   中英

如何在 rust 中进行模式匹配选项? 当前代码不断恐慌

[英]How can I pattern match Option in rust? Current code keeps panicking

我正在研究一个简单的 rust 二进制搜索算法。 它返回一个Option<usize>并且我正在尝试对返回值进行模式匹配。 我的代码目前在None路径上失败。 我很清楚我没有正确使用关键字。 谁能解释我做错了什么?

下面的代码和输出。

代码:

fn find_index( arr: &[usize], find: usize) -> Option<usize> {
   let length = arr.len();
   let mut half = length / 2;
   let mut hind = length - 1;
   let mut lind = 0;
   let mut current = arr[half];

   while  lind <= hind {
       if current == find {
           return Some(half);
       }
       else if current < find{
           lind = half + 1;
       }
       else if current > find {
           hind = half - 1;
       }
        half = (hind + lind) / 2;
        current = arr[half];
   }
   return None;
}

fn grab_array_index(my_arr : &[usize], find: usize) -> usize{ 
    return my_arr.iter()
    .position(|&x| x == find)
    .unwrap();
}

fn main() 
{
    let mut arr = vec![1,2,3,4,5,6];
    let mut find = 3;

    println!("Index of {} is {}", find , grab_array_index(&arr, find));
    match find_index(&arr, find) {
        Some(p) => println!("Here ya go! {}", p),
        None => println!("not in the array >:("),
    }

    arr = vec![1,3,5,7,9,11,13,15,17,19];
    find = 17;

    println!("Index of {} is {}", find , grab_array_index(&arr, find));
    match find_index(&arr, find) {
        Some(p) => println!("Here ya go! {}", p),
        None => println!("not in the array >:("),
    }

    arr = vec![1,3,5,7,9,11,13,15,17,19];
    find = 18;

    println!("Index of {} is {}", find , grab_array_index(&arr, find));
    match find_index(&arr, find) {
        Some(p) => println!("Here ya go! {}", p),
        None => println!("not in the array >:("),
    }
}

输出:

Index of 3 is 2
Here ya go! 2
Index of 17 is 8
Here ya go! 8
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', binary_search.rs:27:6
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

这很令人恐慌,因为在您调用find_index(&arr, find) where find == 18之前,您调用grab_array_index ,它调用了unwrap 由于18不在arr中, grab_array_index在展开时会发生恐慌。 考虑通过删除对 unwrap 的调用,让该函数返回一个Option<usize> unwrap

我假设您这样做是出于教育目的,因此我建议您在对解决方案感到满意时查看std的二进制搜索的源代码,以了解它们如何利用语言特征来概括算法并制作它更有效率。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM