sort
function is defined on slices (and on Vec
s, 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);
}