I am in the process of learning Rust and am still having some issues with borrowing and ownership. I find myself trying to borrow mutable references that are already borrowed as immutable references etc...
I noticed that when I try to iterate over the primes without owning them, I encounter issues trying to modify the composites
hash map. I was able to get around this by calling to_owned
on the vector. Is this the right way to handle this?
I also see that when I build the code, I get warnings about unused code for warning: struct is never constructed: 'Sieve'
and warning: method is never used: 'new'
, am I constructing them incorrectly?
use std::collections::HashMap;
struct Sieve {
composites: HashMap<u64, Vec<u64>>,
x: u64,
}
impl Sieve {
fn new() -> Sieve {
Sieve {
composites: HashMap::new(),
x: 2,
}
}
}
impl Iterator for Sieve {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let x = self.x;
self.x = self.x + 1;
match self.composites.get(&x) {
Some(numbers) => {
for _num in numbers.to_owned() {
self.composites
.entry(x + _num)
.and_modify(|v| v.push(_num))
.or_insert(vec![_num]);
}
self.composites.remove(&x);
self.next()
}
None => {
self.composites.insert(x * x, vec![x]);
Some(x)
}
}
}
}
fn main() {
let mut sieve = Sieve::new();
println!("{:?}", sieve.next()); // 2
println!("{:?}", sieve.next()); // 3
println!("{:?}", sieve.next()); // 5
println!("{:?}", sieve.next()); // 7
}
Here is the code on the Rust playground.
I previously posted a version of the Sieve of Eratosthenes using experimental Rust features, this made it difficult to get feedback on. I have refactored the code to use iterators
main
method would not be called and thus your code would be unused. \$\endgroup\$