I have the mindset keeping my String
s immutable, a single source of truth.
As I take the same mindset into Rust, I find I have to do a lot of cloning.
Since the String
s do not change, all the cloning is unnecessary.
Below there is an example of this and link to the relevant playground.
Borrowing does not seem like an option as I would have to deal with references and their lifetimes. My next thought is to use something like Rc
or Cow
struct. But wrapping all the String
s with something like Rc
feels unnatural. In my limited experience of Rust, I have never seen any exposed ownership/memory management structs, that is Rc
and Cow
. I am curious how a more experience Rust developer would handle such a problem.
Is it actually natural in Rust to expose ownership/memory management structs like Rc
and Cow
? Should I be using slices?
use std::collections::HashSet;
#[derive(Debug)]
enum Check {
Known(String),
Duplicate(String),
Missing(String),
Unknown(String)
}
fn main() {
let known_values: HashSet<_> = [
"a".to_string(),
"b".to_string(),
"c".to_string()]
.iter().cloned().collect();
let provided_values = vec![
"a".to_string(),
"b".to_string(),
"z".to_string(),
"b".to_string()
];
let mut found = HashSet::new();
let mut check_values: Vec<_> = provided_values.iter().cloned()
.map(|v| {
if known_values.contains(&v) {
if found.contains(&v) {
Check::Duplicate(v)
} else {
found.insert(v.clone());
Check::Known(v)
}
} else {
Check::Unknown(v)
}
}).collect();
let missing = known_values.difference(&found);
check_values = missing
.cloned()
.fold(check_values, |mut cv, m| {
cv.push(Check::Missing(m));
cv
});
println!("check_values: {:#?}", check_values);
}