avl*_*den 4 lifetime rust borrow-checker
我想设计一个支持可变迭代器的玩具容器类,但是我无法整理迭代器的生命周期及其对容器的引用.
我试图创建一个最小的非编译示例:
struct Payload {
value: i32,
}
struct Container {
val: Payload,
}
struct IterMut<'a> {
cont: &'a mut Container,
cnt: i32,
}
impl<'a> Container {
fn new() -> Container {
Container { val: Payload { value: 42 } }
}
fn iter_mut(&'a mut self) -> IterMut<'a> {
IterMut {
cont: self,
cnt: 10,
}
}
}
impl<'a> Iterator for IterMut<'a> {
type Item = &'a mut Payload;
fn next<'b>(&'b mut self) -> Option<Self::Item> {
self.cnt -= 1;
if self.cnt < 0 {
return None;
} else {
Some(&mut self.cont.val)
}
}
}
fn main() {
let mut cont = Container::new();
let mut it = cont.iter_mut();
it.next();
}
Run Code Online (Sandbox Code Playgroud)
上面的目的是实现一个真正的愚蠢的容器,它在迭代使用时返回相同的项目10次iter_mut()
.
我无法弄清楚如何实施Iterator::next
.
我确实设法编写了一个常规函数,它实现了与我想要的相同的语义next
:
fn manual_next<'a, 'b>(i: &'a mut IterMut<'b>) -> Option<&'a mut Payload> {
i.cnt -= 1;
if i.cnt < 0 {
return None;
} else {
Some(&mut i.cont.val)
}
}
Run Code Online (Sandbox Code Playgroud)
这没有用,因为我无法设法使其适应实现Iterator::next
,如果没有实现Iterator
,我的容器不能在for循环中迭代,这是我想要的.
不可能按原样实现迭代器,因为它允许您获得对同一项的多个可变引用,从而破坏了Rust的别名/借用规则.借用检查器发现错误的好事!:-)
例如,扩展您的main
示例:
fn main() {
let mut cont = Container::new();
let mut it = cont.iter_mut();
let alias_1 = it.next();
let alias_2 = it.next();
// alias_1 and alias_2 both would have mutable references to cont.val!
}
Run Code Online (Sandbox Code Playgroud)
其他iter_mut
迭代器(例如矢量/切片上的一个)会在每个步骤上返回对不同项的引用,因此不会出现此问题.
如果你真的需要迭代逻辑上可变的东西,你可能能够不可变地迭代,但通过RefCell
或使用内部可变性Cell
.
manual_next
函数编译的原因是你没有被约束到Iterator::next
签名,实际上调用一次是非常安全的(或者如果不保留结果则更安全).但是,如果您尝试保存结果,它会保持IterMut
可靠的借用,您无法再次调用它:
let mut cont = Container::new();
let mut it = cont.iter_mut();
let x = manual_next(&mut it);
manual_next(&mut it); // Error: `it` is still borrowed mutably
Run Code Online (Sandbox Code Playgroud)
相比之下,Iterator::next
有一种类型可以使事物collect
变成矢量.
归档时间: |
|
查看次数: |
531 次 |
最近记录: |