I wrote a function that takes as input a vector of structs and returns a vector of unique strings:
fn filter_uniq(vec: Vec<CourseRequirements>) -> Vec<String> {
let mut uniq = vec
.into_iter()
.map(|course| course.CRS_PREREQ)
.collect::<Vec<String>>();
uniq.sort();
uniq.dedup();
uniq
}
Is there a simpler/more concise way to write this?
You could collect into a HashSet
to dedup instead:
fn filter_uniq(vec: Vec<CourseRequirements>) -> Vec<String> {
vec.into_iter()
.map(|course| course.CRS_PREREQ)
.collect::<HashSet<_>>()
.into_iter()
.collect()
}
5 Likes
I would just keep it as a HashSet
instead of converting back to a Vec<String>
. That way you can keep constant time lookups.
4 Likes
system
closed
#4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.