rustHow to sort a Rust slice by key?
Slices in Rust can be sorted using the sort_by method. This method takes a closure as an argument which is used to compare two elements of the slice. The closure should return Ordering::Less if the first element should appear before the second, Ordering::Greater if the second element should appear before the first, and Ordering::Equal if the two elements are equal.
Example
let mut v = vec![3, 2, 1];
v.sort_by(|a, b| a.cmp(b));
Output example
[1, 2, 3]
Code explanation
let mut v = vec![3, 2, 1];: creates a mutable vectorvwith elements3,2, and1.v.sort_by(|a, b| a.cmp(b));: sorts the vectorvusing thesort_bymethod, which takes a closure as an argument. The closure compares two elementsaandbusing thecmpmethod, which returnsOrdering::Lessifais less thanb,Ordering::Greaterifais greater thanb, andOrdering::Equalifais equal tob.
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 convert a Rust slice to a struct?
- How to split a Rust slice?
- How to iterate over a Rust slice with an index?
- How to push an element to a Rust slice?
- How to fill a Rust slice with a specific value?
- How to reverse a Rust slice?
- How to shift elements in a Rust slice?
- How to slice a hashmap in Rust?
More of Rust
- How to use binary regex in Rust?
- How to match a URL with a regex in Rust?
- How to ignore case in Rust regex?
- How to use regex to match a double quote in Rust?
- How to use Unicode in a regex in Rust?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to parse a file with Rust regex?
- Regex example to match multiline string in Rust?
- How to use negation in Rust regex?
See more codes...