How to get Vec <T> fragment in Rust?
I cannot find in the Vec<T> documentation how to extract a slice from a specified range.
Is there something similar in the standard library:
let a = vec![1, 2, 3, 4]; let suba = a.subvector(0, 2); // Contains [1, 2]; +7
yageek
source share2 answers
The documentation for Vec covers this in a section called slicing .
You can create a slice Vec or array by specifying its Range (or RangeFrom , RangeTo , RangeFull ), for example :
fn main() { let a = vec![1, 2, 3, 4, 5]; // With a start and an end println!("{:?}", &a[1..4]); // With just a start println!("{:?}", &a[2..]); // With just an end println!("{:?}", &a[..3]); // All elements println!("{:?}", &a[..]); } +17
Brian campbell
source shareIf you want to convert the entire Vec to a slice, you can use deref enforcement:
fn main() { let a = vec![1, 2, 3, 4, 5]; let b: &[i32] = &a; println!("{:?}", b); } This coercion is automatically applied when the function is called:
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 this is a little less common:
fn main() { let a = vec![1, 2, 3, 4, 5]; let b = a.as_slice(); println!("{:?}", b); } See also:
- Why is it not recommended to accept a reference to String (& String), Vec (& Vec) or Box (& Box) as an argument to a function?
0
Shepmaster
source share