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 vectorv
with elements3
,2
, and1
.v.sort_by(|a, b| a.cmp(b));
: sorts the vectorv
using thesort_by
method, which takes a closure as an argument. The closure compares two elementsa
andb
using thecmp
method, which returnsOrdering::Less
ifa
is less thanb
,Ordering::Greater
ifa
is greater thanb
, andOrdering::Equal
ifa
is equal tob
.
Helpful links
Related
- How to convert a Rust slice to a fixed array?
- How to convert a u8 slice to a hex string in Rust?
- How to create a slice from a string in Rust?
- How to calculate the sum of a Rust slice?
- How to get the last element of a Rust slice?
- How to convert a slice to a hex string in Rust?
- How to push an element to a Rust slice?
- How to convert a slice into an iter in Rust?
- How to convert a Rust slice of u8 to a string?
- How to convert a Rust slice of u8 to u32?
More of Rust
- How to use regex to match a double quote in Rust?
- How to use regex lookahead in Rust?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to use backslash in regex in Rust?
- How to parse JSON string in Rust?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to make regex case insensitive in Rust?
- How to convert a Rust HashMap to a BTreeMap?
See more codes...