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 push an element to a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to calculate the sum of a Rust slice?
- How to remove elements from a Rust slice?
- How to swap elements in a Rust slice?
- How to convert a vector to a Rust slice?
- How to get the last element of a Rust slice?
- How to convert a Rust slice to a string?
- How to join two Rust slices?
- How to convert a u8 slice to a hex string in Rust?
More of Rust
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- Bitwise XOR operator usage in Rust
- How to use modifiers in a Rust regex?
- How to map with index in Rust
- How to convert a u8 slice to a hex string in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to use an enum in a Rust HashMap?
- How to match the end of a line in a Rust regex?
- How to create a Rust regex from a string?
See more codes...