Is there a better way to do this? Could I use an iterator to achieve the same? I also tried using sort_by
but I have to clone the names
if I do that because names is not mutable.
Would love to see some other examples of how to do this. Also I don’t care about alphabetical order, but would be cool to see how to return for example “a” before “z”.
fn get_shortest<'a>(names: &Vec<&'a str>) -> Option<&'a str> {
if names.len() == 0 {
return None;
}
let mut n = names[0];
for name in names {
if name.len() < n.len() {
n = name;
}
}
return Some(n);
}
fn main() {
let names:Vec<&str> = vec!["Dave", "Latoya", "Ben", "Jake"];
println!("name: {:?}", &names);
match get_shortest(&names) {
Some(name) => {
println!("Shortest: {}!", name);
},
None => {
println!("No result!");
}
};
}