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?

This uses the unstable generator feature.

cargo -V 
cargo 1.35.0-nightly (0e35bd8af 2019-03-13)
#![feature(generators, generator_trait)]

use std::collections::HashMap;
use std::ops::{Generator, GeneratorState};

let mut sieve = || {
    let mut x: u32 = 2;
    let mut composites: HashMap<u32, Vec<u32>> = HashMap::new();

    loop {
        match composites.get(&x) {
            Some(primes) => {
                for _prime in primes.to_owned() {
                        .entry(x + _prime)
                        .and_modify(|v| v.push(_prime))
            None => {
                yield x;
                composites.insert(x * x, vec![x]);

        x = x + 1;
  • \$\begingroup\$ Your code is incomplete and I doubt that doing a review of a code based on an highly unstable feature is useful. Your code does not reflect anymore the last state of this feature BTW. \$\endgroup\$ – French Boiethios Mar 19 '19 at 9:57
  • \$\begingroup\$ @FrenchBoiethios how is the code incomplete? And the documentation is actually incorrect, but I realize that this helps to prove the point you're trying to make. I will refactor this with iterators or a class and post that for review instead. \$\endgroup\$ – kyle Mar 19 '19 at 14:43
  • \$\begingroup\$ Incomplete because we cannot run it. This is difficult to test \$\endgroup\$ – French Boiethios Mar 19 '19 at 16:34
  • 1
    \$\begingroup\$ @Vogel612 — I don't believe this to be a duplicate. This version of the code and the linked duplicate do the same thing but in two greatly different implementation styles. \$\endgroup\$ – Shepmaster Mar 21 '19 at 19:30
  • 1
    \$\begingroup\$ @Shepmaster I assumed the comment by kyle earlier indicated that they were no longer interested in any answers to this question. To make that clear I elected to close this as a duplicate of the newer question to redirect possibly interested reviewers to that new question. This is not a duplicate-closure because I think the questions are duplicates. It's a duplicate-closure because that redirects people to the updated version of the code avoiding stale or unhelpful reviews :) \$\endgroup\$ – Vogel612 Mar 21 '19 at 21:50