Confused: cannot borrow *self as mutable more than once

⚓ Rust    📅 2026-06-19    👤 surdeus    👁️ 1      

surdeus

This is a simplified example:


struct T {
    field: U,
}

struct U {}

impl U {
    fn function1(&mut self) -> Option<&mut U> {
        None
    }

    fn function2(&mut self) -> Option<&mut U> {
        None
    }
}

impl T {
    fn function(&mut self) -> Option<&mut U> {
        {
            if let Some(xxx) = self.field.function1() {
                return Some(xxx);
            }
        }
        {
            if let Some(xxx) = self.field.function2() {
                return Some(xxx);
            }
        }

        None
    }
}

At first glance, it seems the borrow should be finished after first enclosure.
I don't know what I can do. I have no control over U so I can't modify function1 or 2. I want to call function1() and return if Some, and try the function2() otherwise.

What are my options here?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed