这是我所能得到的,使用 rental , 部分基于 How can I store a Chars iterator in the same struct as the String it is iterating on? .这里的区别在于 get_iter
锁定成员的方法必须采用可变的自引用。
我不局限于使用租赁:我对使用 reffers 的解决方案同样满意或 owning_ref .
PhantomData
在这里只是为了 MyIter
与 MyIterable
具有正常的生命周期关系,被迭代的东西。
我也试过改变 #[rental]
至 #[rental(deref_mut_suffix)]
并更改 MyIterable.get_iter
的返回类型至 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]
。
关于iterator - 如何在 Rust 中的锁定结构成员上返回迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664098/