Reborrow error despite variable being unused

⚓ Rust    📅 2026-06-20    👤 surdeus    👁️ 3      

surdeus

struct Str {
    vec: Vec
}

impl Str {
    pub fn change(&mut self) -> Option<&u32> {
        if let Some(a) = self.vec.get() { // first using
            return Some(a);
        }
        self.vec.change(); // second reborrowing error
        None
    }
}

pub struct Vec {}
impl Vec {
    pub fn get(&self) -> Option<&u32> {
        None
    }
    pub fn change(&mut self) {
    }
}

run in playground

Here, output the error:

error[E0502]: cannot borrow `self.vec` as mutable because it is also borrowed as immutable

I‘ve thought about it a lot, but I am still clueless.

4 posts - 2 participants

Read full topic

🏷️ Rust_feed