I'm trying to solve the Spiral Order question on leetcode by splitting off the top and bottom rows one by one, and I ran into a problem with the borrow checker that I can't make sense of. This is the minimal example that creates the compile error:
pub fn f(mut matrix: &mut [Vec<i32>]) {
while let Some((_, remainder)) = matrix.split_first_mut() {
matrix = remainder;
if let Some((_, remainder)) = matrix.split_first_mut() {
matrix = remainder;
}
}
}
And this is my full code, for context of what I'm trying to accomplish:
impl Solution {
pub fn spiral_order(mut matrix: Vec<Vec<i32>>) -> Vec<i32> {
let mut matrix = &mut matrix[..];
if matrix.is_empty() {
return Vec::new();
}
let mut ans = Vec::with_capacity(matrix.len() * matrix[0].len());
while let Some((head, tail)) = matrix.split_first_mut() {
ans.append(head);
matrix = tail;
for row in matrix.iter_mut() {
ans.push(row.pop().unwrap());
}
if let Some((head, tail)) = matrix.split_last_mut() {
matrix = tail;
ans.extend(head.into_iter().rev().map(|&mut x| x));
}
}
ans
}
}
It seems to think that the inner borrow conflicts with the subsequent outer borrow in the next iteration of the loop, but I think it should be okay because I move the remainder back into matrix, so there is a valid &mut [Vec<i32>] in there before the iteration ends. Why is this failing to compile, and how should it be fixed?