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 two members with Rust

1 Answer

0 votes
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]

struct Worker {
   name: String,
   company: String,
   age:u32
}

impl Worker {
    pub fn new(name: String, company: String, age: u32) -> Self {
        Worker {
            name,
            company,
            age
        }
    }
}

fn main() {
    let mut workers = vec![
        Worker::new("Dana".to_string(), "Google".to_string(), 71),
        Worker::new("Avalonr".to_string(), "Microsoft".to_string(), 46),
        Worker::new("R2D2".to_string(), "Apple".to_string(), 98),
        Worker::new("Albus".to_string(), "OpenAI".to_string(), 67),
        Worker::new("3PO".to_string(), "Google".to_string(), 46),
        Worker::new("R1D1".to_string(), "Apple".to_string(), 98),
    ];
    
    workers.sort_unstable_by_key(|item| (item.company.clone(), item.name.clone()));
    
    dbg!(workers);
}
  
  
  
  
/*
run:
  
[example.rs:31] workers = [
    Worker {
        name: "R1D1",
        company: "Apple",
        age: 98,
    },
    Worker {
        name: "R2D2",
        company: "Apple",
        age: 98,
    },
    Worker {
        name: "3PO",
        company: "Google",
        age: 46,
    },
    Worker {
        name: "Dana",
        company: "Google",
        age: 71,
    },
    Worker {
        name: "Avalonr",
        company: "Microsoft",
        age: 46,
    },
    Worker {
        name: "Albus",
        company: "OpenAI",
        age: 67,
    },
]

*/

 



answered Feb 6, 2023 by avibootz
...