Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Modifying and returning reference in match statement
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
🏷️ rust_feed