20

I want to order a Strings vector alphabetically

fn main() {
    let mut vec = Vec::new();
    vec.push("richard");
    vec.push("charles");
    vec.push("Peter");
    println!("{:?}", vec);
}

I tried println!("{:?}", vec.sort()); and println!("{}", vec.sort_by(|a,b| b.cmp(a))); and both response is ().

And I expect the following result

["charles", "Peter", "richard"]
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ricardo Prieto
  • 357
  • 1
  • 3
  • 12

1 Answers1

29

sort function is defined on slices (and on Vecs, as they can Deref to slices) as pub fn sort(&mut self), i.e. it performs sorting in place, mutating the existing piece of data. So to achieve what you're trying to do, you can try the following:

fn main() {
    let mut vec = Vec::new();
    vec.push("richard");
    vec.push("charles");
    vec.push("Peter");
    vec.sort();
    println!("{:?}", vec);
}

Unhappily, this isn't quite the thing you want, since this will sort "Peter" before "charles" - the default comparator of strings is case-sensitive (in fact, it's even locale-agnostic, since it compares basing on Unicode code points). So, if you want to perform case-insensitive sorting, here's the modification:

fn main() {
    let mut vec = Vec::new();
    vec.push("richard");
    vec.push("charles");
    vec.push("Peter");
    vec.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()));
    println!("{:?}", vec);
}
Cerberus
  • 8,879
  • 1
  • 25
  • 40
  • 9
    The line that does the sorting could be more concisely replaced by `vec.sort_by_key(|name| name.to_lowercase());` – asky Aug 15 '21 at 03:20