2

I want to implement something similar to the following:

use std::collections::HashMap;
use std::collections::hash_map::Keys as HashMapKeys;
use std::sync::{Mutex, MutexGuard};

struct MyIterable {
    data: Mutex<HashMap<i32, i32>>,
}

struct MyIter<'a> {
    lock: MutexGuard<'a, HashMap<i32, i32>>,
    inner: HashMapKeys<'a, i32, i32>,
}

impl MyIterable {
    fn iter(&self) -> MyIter<'_> {
        let lock = self.data.lock().unwrap();
        let inner = lock.keys();
        MyIter { lock, inner }
    }
}

impl<'a> Iterator for MyIter<'a> {
    type Item = i32;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

For obvious reasons, the code above cannot compile. MyIter::inner is referencing MyIter::lock in the borrow checker's eyes, which makes MyIter a self-referential struct.

I knows the rental crate may be able to solve this problem. If so, how does rental solve it? How is the lifetime parameter of MyIter::inner elided?

Lancern
  • 403
  • 2
  • 9

0 Answers0