首页 > 解决方案 > 如何在 Rust 中的锁定结构成员上返回迭代器?

问题描述

这是我所能得到的,使用rent,部分基于如何将 Chars 迭代器存储在与其迭代的 String 相同的结构中?. 这里的区别是get_iter锁定成员的方法必须采用可变的自引用。

我与使用租赁无关:我对使用 refers 或 owning_ref 的解决方案同样满意

出现PhantomData在这里只是为了与被迭代的事物具有MyIter正常的生命周期关系。MyIterable

我还尝试更改#[rental]to#[rental(deref_mut_suffix)]并更改 to 的返回类型,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);
}

标签: iteratorrustmutex

解决方案


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


推荐阅读