In Learning Rust With Entirely Too Many Linked Lists, the iter()
creates an iterator:
impl<T> List<T> {
pub fn iter(&self) -> Iter<T> {
Iter { next: self.head.as_ref().map(|node| &**node) }
}
}
I try to test if the iterator prevents further modification on the list:
let mut list = List::new();
list.push(1);
let mut iter = list.iter();
list.pop();
The compiler reports an error:
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();
^~~~
It seems that Rust would indeed prevent unsafe operations, but from the syntax, why does list.iter()
borrow the list
? In the method, it just return the reference of the head element.