Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,817 answers

573 users

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
...