我如何 return 在 Rust 中锁定结构成员的迭代器?

How can I return an iterator over a locked struct member in Rust?

这是我所能得到的,使用 rental, partly based on How can I store a Chars iterator in the same struct as the String it is iterating on?。这里的区别在于锁定成员的 get_iter 方法必须采用可变的自引用。

我不依赖于租赁:我对使用 reffers or owning_ref 的解决方案同样满意。

PhantomData 出现在这里只是为了让 MyIterMyIterable 具有正常的生命周期关系,被迭代的东西。

我还尝试将 #[rental] 更改为 #[rental(deref_mut_suffix)] 并将 MyIterable.get_iter 的 return 类型更改为 Box<Iterator<Item=i32> + 'a> 但这给了我其他生命周期错误我无法破译的宏

#[macro_use]
extern crate rental;

use std::marker::PhantomData;

pub struct MyIterable {}

impl MyIterable {
    // In the real use-case I can't remove the 'mut'.
    pub fn get_iter<'a>(&'a mut self) -> MyIter<'a> {
        MyIter {
            marker: PhantomData,
        }
    }
}

pub struct MyIter<'a> {
    marker: PhantomData<&'a MyIterable>,
}

impl<'a> Iterator for MyIter<'a> {
    type Item = i32;
    fn next(&mut self) -> Option<i32> {
        Some(42)
    }
}

use std::sync::Mutex;

rental! {
    mod locking_iter {
        pub use super::{MyIterable, MyIter};
        use std::sync::MutexGuard;

        #[rental]
        pub struct LockingIter<'a> {
            guard: MutexGuard<'a, MyIterable>,
            iter: MyIter<'guard>,
        }
    }
}

use locking_iter::LockingIter;

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

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.rent_mut(|iter| iter.next())
    }
}

struct Access {
    shared: Mutex<MyIterable>,
}

impl Access {
    pub fn get_iter<'a>(&'a self) -> Box<Iterator<Item = i32> + 'a> {
        Box::new(LockingIter::new(self.shared.lock().unwrap(), |mi| {
            mi.get_iter()
        }))
    }
}

fn main() {
    let access = Access {
        shared: Mutex::new(MyIterable {}),
    };
    let iter = access.get_iter();
    let contents: Vec<i32> = iter.take(2).collect();
    println!("contents: {:?}", contents);
}

正如用户 rodrigo 在评论中指出的那样,解决方案只是将 #[rental] 更改为 #[rental_mut]