rustHow to get all elements of a Rust slice except the last one?
To get all elements of a Rust slice except the last one, you can use the .split_last()
method. This method returns a tuple of two slices, the first one containing all elements except the last one, and the second one containing the last element.
let v = [1, 2, 3, 4, 5];
let (first, last) = v.split_last().unwrap();
println!("First slice: {:?}", first);
println!("Last element: {:?}", last);
Output example
First slice: [1, 2, 3, 4]
Last element: [5]
Code explanation
let v = [1, 2, 3, 4, 5];
: This line creates a slicev
containing the elements1
,2
,3
,4
, and5
.let (first, last) = v.split_last().unwrap();
: This line uses the.split_last()
method to split the slicev
into two slices,first
andlast
.first
contains all elements except the last one, andlast
contains the last element.println!("First slice: {:?}", first);
: This line prints the contents of thefirst
slice.println!("Last element: {:?}", last);
: This line prints the contents of thelast
slice.
Helpful links
Related
- How to iterate over a Rust slice with an index?
- How to convert a Rust slice of u8 to a string?
- How to convert a Rust slice of u8 to u32?
- How to make a Rust slice unique?
- How to convert a Rust slice to a fixed array?
- How to convert a Rust slice to a tuple?
- How to convert a Rust slice to a struct?
- How to calculate the sum of a Rust slice?
- How to split a Rust slice?
- How to remove elements from a Rust slice?
More of Rust
- How to use regex with bytes in Rust?
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to match the end of a line in a Rust regex?
- How to calculate the inverse of a matrix in Rust?
- How to get an entry from a HashSet in Rust?
- How to split a string by regex in Rust?
- How to implement PartialEq for a Rust HashMap?
See more codes...