Here is a minimal example for some behavior that I came across:
pub struct PrimeEngine {
primes: Vec<uint>,
}
pub struct PrimeIterator<'a> {
engine: &'a mut PrimeEngine,
index: uint
}
impl PrimeEngine {
pub fn new() -> PrimeEngine {
PrimeEngine { primes: vec![] }
}
pub fn is_prime(&mut self, x: uint) -> bool {
true
}
pub fn iter<'a>(&'a mut self) -> PrimeIterator<'a> { // '
PrimeIterator { engine: self, index: 0 }
}
fn more_primes(&mut self) {
}
}
impl<'a> Iterator<uint> for PrimeIterator<'a> {
fn next(&mut self) -> Option<uint> {
if self.engine.primes.len() <= self.index {
self.engine.more_primes();
}
let i = self.index;
self.index += 1;
Some(self.engine.primes[i])
}
}
The following code does not compile because it tries to make two mutable roles engine, once when creating a closure and again when creating an iterator:
fn test1() {
let mut engine = PrimeEngine::new();
engine.iter().take(5).inspect(|x| {
assert!(engine.is_prime(*x))
});
}
This code, however, compiles:
fn test2() {
let mut engine = PrimeEngine::new();
for x in engine.iter().take(5) {
assert!(engine.is_prime(x))
}
}
And I have no idea why. To create, Iteratoryou need to create a mutable borrow engine, which should prevent him from making a mutable borrow, necessary for the call is_prime. Is this allowed for some reason? Or is this a mistake?
source
share