How to sort a vector of structs by string member with Rust

1 Answer

0 votes
#[derive(Debug)]
 
struct Example {
    s: String,
    i: i8,
}
 
fn main() {
    let mut ex: Vec<Example> = Vec::new();
     
    ex.push(Example { s: "ccc".to_string(), i: 1 });
    ex.push(Example { s: "aaa".to_string(), i: 2 });
    ex.push(Example { s: "bbb".to_string(), i: 3 });
 
    ex.sort_by_key(|item| item.s.clone());
      
    dbg!(ex);
}
 
 
 
 
/*
run:
 
[example.rs:17] ex = [
    Example {
        s: "aaa",
        i: 2,
    },
    Example {
        s: "bbb",
        i: 3,
    },
    Example {
        s: "ccc",
        i: 1,
    },
]
 
*/

 



answered Feb 6, 2023 by avibootz
edited Feb 6, 2023 by avibootz
...