Proper way to use sort_by_key for struct field?
⚓ Rust 📅 2026-02-27 👤 surdeus 👁️ 1I have a simple struct:
#[derive(Debug, Clone)]
pub struct LabeledStrings {
label: String,
strings: Vec<String>,
}
impl LabeledStrings {
pub fn new(label: String, strings: Vec<String>) -> LabeledStrings {
LabeledStrings { label, strings }
}
pub fn get_label(self) -> String {
self.label
}
pub fn get_vals(self) -> Vec<String> {
self.strings
}
}
I have a Vector of these things, and I want to sort it by the labels:
let mut keys: Vec<LabeledStrings> = ...
keys.sort_by_key(|ls| ls.clone().get_label());
When I tried it without the .clone() the compiler complained that I was moving ls. I am missing something in how to use methods like map, filter, sort_by_key when the elements are structures, and thus the parameters are references to structures. to get rid of the need to clone, do I need to make the methods take &self instead of self?
Thanks,
Joel
11 posts - 6 participants
🏷️ Rust_feed