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 slicevcontaining the elements1,2,3,4, and5.let (first, last) = v.split_last().unwrap();: This line uses the.split_last()method to split the slicevinto two slices,firstandlast.firstcontains all elements except the last one, andlastcontains the last element.println!("First slice: {:?}", first);: This line prints the contents of thefirstslice.println!("Last element: {:?}", last);: This line prints the contents of thelastslice.
Helpful links
Related
- How to convert a Rust slice of u8 to a string?
- How to convert a Rust slice of u8 to u32?
- How to calculate the sum of a Rust slice?
- How to map a Rust slice?
- How to slice a hashmap in Rust?
- Does Rust perform bounds checking on slices?
- How to split a Rust slice?
- How to remove elements from a Rust slice?
- How to reverse a Rust slice?
- How to push an element to a Rust slice?
More of Rust
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use regex captures in Rust?
- How to use binary regex in Rust?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to lock a Rust HashMap?
- How to compare two Rust HashMaps?
- How to convert a Rust slice of u8 to a string?
- How to iterate over a Rust HashMap?
See more codes...