【发布时间】:2019-01-22 15:11:25
【问题描述】:
已就该主题提出了多个问题:
- Returning iterator of a Vec in a RefCell
- How do I return an iterator that has a reference to something inside a RefCell?
- How can I return an iterator over a locked struct member in Rust?
答案或多或少:不可能(没有不安全)。
我自己尝试了不安全的变体,想问问这种方式是否安全。
我的想法是我将守卫包装在一个实现Iterator 的结构中。除了守卫之外,还存储了一个迭代器,该迭代器将从存储的守卫中创建:
struct MapIter<'a> {
guard: RwLockReadGuard<'a, HashMap<i32, i32>>,
iter: Iter<'a, i32, i32>,
}
它是用这些行创建的:
impl<'a> MapIter<'a> {
fn new(map: &'a RwLock<HashMap<i32, i32>>) -> Box<Self> {
// create a `box Self`
// the iterator remains uninitialized.
let mut boxed = Box::new(Self {
guard: map.read().expect("ToDo"),
iter: unsafe { mem::uninitialized() },
});
// create the iterator from `box Self`.
boxed.iter = unsafe {
(*(&boxed.guard as *const RwLockReadGuard<'a, HashMap<i32, i32>>)).iter()
};
boxed
}
}
现在可以实现Iterator:
impl<'a> Iterator for MapIter<'a> {
type Item = (&'a i32, &'a i32);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
}
这段代码安全吗?
在playground 上查看此代码。
另外我得到一个琐碎的演员表警告
warning: trivial cast: warning: trivial cast: `&std::sync::RwLockReadGuard<'_, std::collections::HashMap<i32, i32>>` as `*const std::sync::RwLockReadGuard<'a, std::collections::HashMap<i32, i32>>`. Cast can be replaced by coercion, this might require type ascription or a temporary variable
|
| unsafe { (*(&boxed.guard as *const RwLockReadGuard<'a, HashMap<i32, i32>>)).iter() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
如何解决这个问题?
【问题讨论】: