The exclusive borrowing is done in a dedicated scope. Why is still affecting the for loop following it ?
#[derive(Clone, Default)]
struct Polygon {
points: Vec<(i64, i64)>,
}
fn main() {
let mut prev_crossing = None;
let mut polygons: Vec<Polygon> = vec![Polygon::default(); 10];
for i in 0..10 {
{
let polygon = &mut polygons[i];
polygon.points.sort_by(|_, _| todo!());
drop(polygon);
// try using a function, still errors
// sort(&mut polygons[i]);
}
for crossing in polygons[i].points.iter() {
if prev_crossing.is_none() {
prev_crossing = Some(crossing);
} else {
todo!();
}
}
}
}
fn sort(polygon: &mut Polygon) {
polygon.points.sort_by(|_, _| todo!());
}
error[E0502]: cannot borrow `polygons` as mutable because it is also borrowed as immutable
--> src/main.rs:12:32
|
12 | let polygon = &mut polygons[i];
| ^^^^^^^^ mutable borrow occurs here
...
19 | for crossing in polygons[i].points.iter() {
| -------- immutable borrow occurs here
20 | if prev_crossing.is_none() {
| ------------- immutable borrow later used here