Hello everyone! I'm back with another beginner question!
So, this time the error is inside the count_votes
method in two different lines.
This method tries to count the the frequency of the different votes inside of total_votes
using a HashMap
.
The map is filled up with Option<T>
votes as keys associated to usize
counters values. The counters increments every time a vote repeats. It's a pretty standard algorithm.
Then count_votes
returns the most frequent vote wrapped inside a Ok(Scrutiny())
instance.
Here is the code:
pub struct Election<T> {
pub voters: HashMap<&'static str, Option<T>>,
pub winner_threshold: u32,
}
impl<T> Election<T> {
pub fn new(voters: &[&'static str], winner_threshold: u32) -> Election<T> {
let voters: HashMap<&'static str, Option<T>> = (*voters).iter()
.map(|&v| (v, None))
.collect();
Election { voters, winner_threshold, }
}
pub fn vote(&mut self, voter: &'static str, vote: T) {
if let Some(voter) = self.voters.get_mut(voter) {
voter.get_or_insert(vote);
}
}
pub fn count_votes(self) -> Result<Scrutiny<T>, Election<T>> {
let total_votes = self.voters.values();
let unvoted = total_votes.filter(|v| !v.is_some())
.count();
if unvoted > 0 {
Err(self)
} else {
let mut votes_counter: HashMap<Option<T>, usize> = new();
for vote in total_votes {
// this line has a compile error
let vote_count = votes_counter.entry(vote).or_insert(0);
*vote_count += 1;
}
// this line has a compile error
let result = votes_counter.iter().max_by(|&(k, v)| *v);
Ok(Scrutiny { result })
}
}
}
pub struct Scrutiny<T> {
result: T,
}
impl<T> Scrutiny<T> {
pub fn result(&self) -> &T {
&self.result
}
}
The first error that I encountered, and that I don't know if I'm not setting properly the pointer level of votes_counter
or just HashMap
can't use Some(T) as keys, is the following:
error[E0599]: no method named `entry` found for struct `std::collections::HashMap<std::option::Option<T>, usize>` in the current scope
--> src/core/election.rs:37:48
|
37 | let vote_count = votes_counter.entry(vote).or_insert(0);
| ^^^^^ method not found in `std::collections::HashMap<std::option::Option<T>, usize>`
|
= note: the method `entry` exists but the following trait bounds were not satisfied:
`std::option::Option<T>: std::cmp::Eq`
`std::option::Option<T>: std::hash::Hash`
And the second one, I think it must be an iterator issue that I unable to solve due to my short experience using them. I've tried different approaches going back and forth but I haven't seen the light at the end of the tunnel yet.
error[E0593]: closure is expected to take 2 arguments, but it takes 1 argument
--> src/core/election.rs:41:40
|
41 | ... .max_by(|&(k, v)| *v);
| ^^^^^^ --------- takes 1 argument
| |
| expected closure that takes 2 arguments
Thank you very much for your time to review my code.