rap-2-h
rap-2-h

Reputation: 31968

How do I slice an array with an i32 limit?

I'm trying to slice an array with a dynamic boundary:

fn main() {
    let n: i32 = 2;
    let a = [1, 2, 3];
    println!("{:?}", &a[0..n]);
}

It gives me the following error:

error: the trait bound [_]: std::ops::Index<std::ops::Range<i32>> is not satisfied

I don't know what to do with this error. It seems I can't use a i32 to slice an array?

Upvotes: 2

Views: 907

Answers (1)

malbarbo
malbarbo

Reputation: 11177

You can check in slice docs (search for Index<Range) that Index trait is only implemented for usize ranges, so you cannot use a Range<i32>.

One possibility is to cast the i32 for usize:

fn main() {
    let n: i32 = 2;
    let a = [1,2,3];
    println!("{:?}", &a[0..n as usize]); 
}

but you should take care because the cast is not checked, a negative i32 value can be cast to usize without an error. You can create a function to do a checked conversion or use a crate (for example num::ToPrimitive).

In the future, Rust will have checked conversion in the standard library.

Upvotes: 8

Related Questions