Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created February 4, 2024 00:01
Show Gist options
  • Save fancellu/5df3f890738a0f78b88eb68e18034c7b to your computer and use it in GitHub Desktop.
Save fancellu/5df3f890738a0f78b88eb68e18034c7b to your computer and use it in GitHub Desktop.
Rust sort Vec of &str or String, in place, case insensitive
fn insensitive_sort<T: AsRef<str>>(users: &mut Vec<T>) {
users.sort_by_cached_key(|a: &T| a.as_ref().to_lowercase());
}
fn main() {
let mut users: Vec<String> = vec![String::from("zzz"), String::from("xxx")];
insensitive_sort(&mut users);
println!("{:?}", users);
let mut users: Vec<&str> = vec!["Todd", "amy"];
insensitive_sort(&mut users);
println!("{:?}", users);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment