Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vector

rust

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]; 
like image 869
yageek Avatar asked Sep 30 '16 07:09

yageek


People also ask

How do you add slices in Rust?

As a result, you cannot use a Rust slice to insert, append or remove elements from the underlying container. Instead, you need either: to use a mutable reference to the container itself, to design a trait and use a mutable reference to said trait.

How do I make a new vector in Rust?

In Rust, there are several ways to initialize a vector. In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new();

How do you clear a vector in Rust?

To remove all elements from a vector in Rust, use . retain() method to keep all elements the do not match. let mut v = vec![


1 Answers

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[..]); } 
like image 178
Brian Campbell Avatar answered Oct 13 '22 04:10

Brian Campbell