RamGorurerChhana
RamGorurerChhana

Reputation: 85

the trait SliceIndex<[i32]> is not implemented for [RangeFrom<{integer}>; 1]

I have written a function which takes a generic parameter T with bound AsRef[i32]. Now I want to slice the input further inside my function with get method. But rust compiler would not let me use 1.. range to slice. I can use split_at method to split the slice. That will work. But my question is why can't I use array.as_ref().get([1..]) in this case? Do I need to add any other trait bounds to the generic type to make it work? If I do get with one index like array.as_ref().get(0) that works fine.

Here is my code -

fn find<T>(array: T, key: i32) -> Option<usize> 
where 
    T: AsRef<[i32]>,
{
    let arr = array.as_ref().get([1..]);
    println!("slicing successful");
    
    None
}

fn main() {
    let arr = [1, 2, 3];
    find(arr, 1);
}

Playground link.

Upvotes: 0

Views: 947

Answers (1)

jthulhu
jthulhu

Reputation: 8657

You are confusing two syntax. The first one is the most commonly used to index a slice:

let arr = array.as_ref()[1..];

This is just syntax sugar for

let arr = array.as_ref().index(1..);

Note that for the second version to work, you need to have the std::ops::Index trait in scope.

This will not work as is because it returns a slice [i32], and [i32]: !Sized. Therefore you need to add a level of indirection:

let arr = &array.as_ref()[1..];

See the playground.

The second possible way is to use the get method of slices:

let arr = array.as_ref().get(1..);

See the playground.

Upvotes: 5

Related Questions