Use AsRef to accept Vec/Array/Slice argument

Hi, I wrote a simple binary search program which accept Slice argument. And I want to use AsRef to accept Vec/Array/Slice argument. I followed compiler suggestion to add "ExactSizeIterator" trait and compile failed. Any suggestion? Thanks!

fn add_option_usize(a: &Option<usize>, b: &Option<usize>) -> Option<usize> {
    if a.is_none() || b.is_none() {
        return None;
    } else {
        return Some(a.unwrap() + b.unwrap());
    }
}

// array can be Vec, Array, Slice
//pub fn find(array: &[i32], key: i32) -> Option<usize> {
pub fn find<T: ExactSizeIterator + AsRef<[i32]>>(array: T, key: i32) -> Option<usize> {
    match array.len() {
        0 => None,
        _ => {
            let mid = array.len() / 2;
            if array[mid] == key {
                Some(mid)
            } else if array[mid] > key {
                find(&array[0..mid], key)
            } else {
                add_option_usize(&Some(mid + 1), &find(&array[mid + 1..], key))
            }
        }
    }
}

error[E0608]: cannot index into a value of type `T`
  --> src\lib.rs:16:16
   |
16 |             if array[mid] == key {
   |                ^^^^^^^^^^

In order to get the slice, you need to call array.as_ref(). Also, you don't actually need the iterator trait bound; you can get the length from the slice and you're not iterating.

Here's your code after applying those changes.

1 Like

Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.