Modifying and returning reference in match statement

⚓ Rust    📅 2025-07-21    👤 surdeus    👁️ 3      

surdeus

Below is a simplified version of a bit of code I'm struggling with.

enum Bar {
    NotReady,
    Ready(u64),
}

struct Foo {
    bar: Bar,
}

impl Foo {
    fn baz(&mut self) -> Option<&u64> {
        match &mut self.bar {
            Bar::NotReady => {
                self.bar = Bar::Ready(123);
                None
            }
            Bar::Ready(val) => Some(val),
        }
    }
}

The compiler error I get is:

105 |     fn baz(&mut self) -> Option<&u64> {
    |            - let's call the lifetime of this reference `'1`
106 |         match &mut self.bar {
    |               ------------- `self.bar` is borrowed here
107 |             Bar::NotReady => {
108 |                 self.bar = Bar::Ready(123);
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.bar` is assigned to here but it was already borrowed
...
111 |             Bar::Ready(val) => Some(val),
    |                                --------- returning this value requires that `self.bar` is borrowed for `'1`

I don't completely understand this error message. Can someone please explain it and offer an idiomatic way of accomplishing something like this?

8 posts - 3 participants

Read full topic

🏷️ rust_feed