For range on slice on aray yields [T] instead of T?

Starting my Rust journey - might be a noob question...
I wand to iterate on part of a slice knowing how many items of that slice i want to iterate on. How can I achieve that?

What i've tried is to have a for of on a range [0..only] but indexing my slice with the produced index gives me a [T] instead of a T. How come? what i am missing?

fn in_slice(slice: &[u8], only: usize) {
    for index in [0..only] {
        println!("{}", slice[index]); // slice[index] here is a [u8] and not a u8
    }
}

fn main() {
    in_slice(&[1, 2, 3], 2)
}

You wrote [0..only]. This is not an integer range, it's an arrays with a single element, and that element is a range. So on the only iteration step you have index = 0..only, and indexing a slice with a range gives you a subslice of type [T] (which can't be used by value since it's unsized, so you get a compile error).

The fix is for index in 0..only { .. }

2 Likes

indeed a noob question
thanks a lot

Also, the more idiomatic way is to iterate directly over a subslice unless you need to do something with the index:

for item in &slice[0..only] {
     println!("{item}");
}
2 Likes