Back to TILs

Rust slices

rust slices ranges

Table of contents

Slices are a dynamically sized view into a sequence.

Therefore, you can have a slice which references an array or a vector and treat them the same.

fn main() {
    //              0   1   2   3   4
    let numbers = [10, 20, 30, 40, 50];
    let subset_1 = &numbers[1..3]; //  20, 30
    let subset_2 = &numbers[1..=3]; // 20, 30, 40

    println!("subset_1");
    for n in subset_1 {
        println!("{n}");
    }

    println!("subset_2");
    for n in subset_2 {
        println!("{n}");
    }

    println!("numbers_2");
    let numbers_2: Vec<u8> = (1..5).collect(); // 1, 2, 3, 4
    for n in numbers_2 {
        println!("{n}");
    }
}

Possible output

subset_1
20
30
subset_2
20
30
40
numbers_2
1
2
3
4

References