【发布时间】:2016-07-03 21:06:07
【问题描述】:
在Learning Rust With Entirely Too Many Linked Lists 中,iter() 创建了一个迭代器:
impl<T> List<T> {
pub fn iter(&self) -> Iter<T> {
Iter { next: self.head.as_ref().map(|node| &**node) }
}
}
我尝试测试迭代器是否会阻止对列表的进一步修改:
let mut list = List::new();
list.push(1);
let mut iter = list.iter();
list.pop();
编译器报错:
list2.rs:114:1: 114:5 error: cannot borrow `list` as mutable because it is also borrowed as immutable [E0502]
list2.rs:114 list.pop();
^~~~
list2.rs:113:24: 113:28 note: previous borrow of `list` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `list` until the borrow ends
list2.rs:113 let mut iter = list.iter();
^~~~
看来Rust确实会阻止不安全的操作,但是从语法上看,list.iter()为什么要借用list呢?在方法中,它只是返回头部元素的引用。
【问题讨论】:
标签: rust