How do I get a slice of a Vec<T> in Rust?

VectorRust

Vector Problem Overview


I can not find within the documentation of Vec<T> how to retrieve a slice from a specified range.

Is there something like this in the standard library:

let a = vec![1, 2, 3, 4];
let suba = a.subvector(0, 2); // Contains [1, 2];

Vector Solutions


Solution 1 - Vector

The documentation for Vec covers this in the section titled "slicing".

You can create a slice of a Vec or array by indexing it with a Range (or RangeInclusive, RangeFrom, RangeTo, RangeToInclusive, or RangeFull), for example:

fn main() {
    let a = vec![1, 2, 3, 4, 5];

    // With a start and an end
    println!("{:?}", &a[1..4]);

    // With a start and an end, inclusive
    println!("{:?}", &a[1..=3]);

    // With just a start
    println!("{:?}", &a[2..]);

    // With just an end
    println!("{:?}", &a[..3]);

    // With just an end, inclusive
    println!("{:?}", &a[..=2]);

    // All elements
    println!("{:?}", &a[..]);
}

Solution 2 - Vector

If you wish to convert the entire Vec to a slice, you can use deref coercion:

fn main() {
    let a = vec![1, 2, 3, 4, 5];
    let b: &[i32] = &a;

    println!("{:?}", b);
}

This coercion is automatically applied when calling a function:

fn print_it(b: &[i32]) {
    println!("{:?}", b);
}

fn main() {
    let a = vec![1, 2, 3, 4, 5];
    print_it(&a);
}

You can also call Vec::as_slice, but it's a bit less common:

fn main() {
    let a = vec![1, 2, 3, 4, 5];
    let b = a.as_slice();
    println!("{:?}", b);
}

See also:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyageekView Question on Stackoverflow
Solution 1 - VectorBrian CampbellView Answer on Stackoverflow
Solution 2 - VectorShepmasterView Answer on Stackoverflow