I am trying to implement Iterator
on an enum, such that it switches between variants on each .next()
call. I want to reuse some data which is common to each variant, by assigning it to the newly-assigned enum value.
In the following example, I would like to switch the variant between E::A
and E::B
on each method call, and reuse the similar string value held within the enum:
enum E {
A(String),
B(String)
}
impl Iterator for E {
/* ... */
fn next(&mut self) -> /* ... */ {
*self = match *self {
E::A(ref s) => E::B(*s),
E::B(ref s) => E::A(*s),
};
/*...*/
}
}
But I get an error about moving out a member of borrowed self
:
error: cannot move out of borrowed content [E0507]
main.rs:11 E::A(ref s) => E::B(*s),
Since self
is being atomically replaced, the moving-out of its content should be logically sound, but the borrow checker does not detect this.
Currently I am .clone()
ing the field I wish to move instead, but this is wasteful.
I have considered the use of mem::swap
, which allows atomic swaps of borrowed content; but it looks as though this only works if the two swapped locations exist simultaneously.
Is what I want possible, without the use of unsafe
?