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 calculate the sum of a Rust slice?
- How to convert a slice of bytes to a string in Rust?
- How to convert a slice into an iter in Rust?
- How to get the first element of a slice in Rust?
- How to extend a Rust slice?
- How to check for equality between Rust slices?
- How to cast a Rust slice?
- What are the characters in a Rust slice?
- How to create a subslice from a Rust slice?
- How to fill a Rust slice with a specific value?
More of Rust
- How to match whitespace with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
- How to match digits with regex in Rust?
- How to use backslash in regex in Rust?
- How to use regex to match a double quote in Rust?
- How to create a Rust HashMap with a string key?
- How to remove an element from a Rust HashMap if a condition is met?
- How to use a Rust HashMap in a multithreaded environment?
- How to use a HashBrown with a Rust HashMap?
See more codes...