I have a two-case enum:
#[derive(Debug)]
pub enum Enum {
Str(String),
Fields { len: u32, opt: Option<String> },
}
use Enum::*;
I want to update my enum in-place, depending on its value. This works at first:
pub fn update(x: &mut Enum) {
match x {
&mut Str(ref mut s) => { s.push('k'); }
&mut Fields { ref mut len, ref mut opt } => { *len += 1; }
}
}
I would like to switch the enum type in some cases:
pub fn update(x: &mut Enum) {
match x {
&mut Str(ref mut s) => { s.push('k'); }
&mut Fields { ref mut len, ref mut opt } => {
if *len < 5 {
*x = Str(String::from("default"));
} else {
*len += 1;
}
}
}
}
Now the borrow checker is unhappy:
error[E0506]: cannot assign to `*x` because it is borrowed
--> src/main.rs:14:15
|
12 | &mut Fields { ref mut len, ref mut opt } => {
| ----------- borrow of `*x` occurs here
13 | if *len < 5 {
14 | *x = Str(String::from("default"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `*x` occurs here
In this case, we can work around the problem by assigning to a temporary variable:
pub fn update(x: &mut Enum) {
let mut update_hack: Option<Enum> = None;
match x {
&mut Str(ref mut s) => { s.push('k'); }
&mut Fields { ref mut len, ref mut opt } => {
if *len < 5 {
update_hack = Some(Str(String::from("default")));
} else {
*len += 1;
}
}
}
match update_hack {
None => {},
Some(to_return) => { *x = to_return; },
}
}
But I want to use some of my data in update_hack
.
match x {
&mut Str(ref mut s) => { s.push('k'); }
&mut Fields { ref mut len, ref mut opt } => {
match opt {
&mut Some(ref s) => { update_hack = Some(Str(*s)) },
&mut None => { *len += 1 },
}
}
}
And now we're in more serious trouble:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:16:62
|
16 | &mut Some(ref s) => { update_hack = Some(Str(*s)) },
| ^^ cannot move out of borrowed content
This time I'm not sure how to fix the problem. It feels like we're piling on hacks when there should be a clean way. What's the idiomatic solution?