iterator - 如何在 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);
}
解决方案
正如用户rodrigo在评论中指出的那样,解决方案只是更改#[rental]
为#[rental_mut]
.
推荐阅读
- json - 如何在 bash shell 中合并具有唯一 InstanceId 的对象?
- javascript - 如何在 Javascript 中更新嵌套的 JSON 键?
- javascript - 如果持续时间为 24 小时,Moment.js 返回 2 天
- asynchronous - 未取消 未来
- database - 网络性能对数据库 (RDS) 的影响
- python-3.x - 从具有法线的点云到多面体的 pyntcloud
- javascript - 如何计算鼠标悬停在正在绘制的元素上时相对于绘图区域的位置
- javascript - HTML表格中的下拉菜单不显示链接
- maven - 如何在 maven pom 中自动设置 scm 连接?
- php - Laravel 5.7 - 未定义的偏移量:1