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 push an element to a Rust slice?
- How to convert a Rust slice of u8 to a string?
- How to calculate the sum of a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to remove elements from 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 slice of bytes to a string in Rust?
- How to convert a u8 slice to a hex string in Rust?
- How to convert a Rust slice of u8 to u32?
More of Rust
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to use an enum in a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to use captures_iter with regex in Rust?
- How to use backslash in regex in Rust?
- How to perform matrix operations in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to implement PartialEq for a Rust HashMap?
See more codes...