Cannot modify a struct field from implementation: “cannot borrow immutable borrowed content as mutable”

前端 未结 1 1734
猫巷女王i
猫巷女王i 2021-01-14 07:33

I\'m trying to implement an iterator which will yield prime numbers. I store already found prime numbers in a Vec.

Here\'s my implementation:

相关标签:
1条回答
  • 2021-01-14 07:53

    Your PrimesIterator type contains a non-mutable reference to a Vec<u64>. You need to declare it as a mutable reference:

    struct PrimesIterator<'a> {
        primes: &'a mut Vec<u64>,
        index: usize,
    }
    

    This will of course require you to also modify the iter() function to make sure it passes a mutable reference:

    impl Primes {
        fn new() -> Primes {
            Primes { primes: vec!(2, 3) }
        }
    
        fn iter(&mut self) -> PrimesIterator {
            PrimesIterator { primes: &mut self.primes, index : 0 }
        }
    }
    
    0 讨论(0)
提交回复
热议问题