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 convert a Rust slice of u8 to u32?
- How to convert a u8 slice to a hex string in Rust?
- How to convert a Rust slice of u8 to a string?
- How to get the last element of a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to convert a slice of bytes to a string in Rust?
- How to convert a slice to a hex string in Rust?
- How to convert a vector to a Rust slice?
- How to calculate the sum of a Rust slice?
- How to create a slice from a string in Rust?
More of Rust
- How to parse JSON string in Rust?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to get a capture group using Rust regex?
- How to use regex to match a group in Rust?
- How to match the end of a line in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to use a tuple as a key in a Rust HashMap?
- How to calculate the inverse of a matrix in Rust?
- How to replace strings using Rust regex?
See more codes...