#Change nested Enum Variant with a `&mut self` with attached Data.

6 messages · Page 1 of 1 (latest)

woven heron
#

I'm trying to build a State Machine that holds a Token in some States. Is it possible to do this using only &mut self?

struct StateMachine{
    variants:Variants,
}
enum State{
    A(Token),
    B(Token),
}
struct Token{}

impl StateMachine{
    fn transition(&mut self){
        match self.variants {
            State::A(token) => {
                self.variants = State::B(token);
            },
            _ => todo!(),
        }
    }
}

The Error:

error[E0507]: cannot move out of `self.variants.0` which is behind a mutable reference
  --> testing/src/main.rs:20:15
   |
20 |         match self.variants {
   |               ^^^^^^^^^^^^^ help: consider borrowing here: `&self.variants`
21 |             Variants::A(token) => {
   |                         -----
   |                         |
   |                         data moved here
   |                         move occurs because `token` has type `Token`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0507`.
supple lotus
#

you will have to add a Temporary state

#

and typically just panic if you ever encounter it

spring tinsel
#

If every state is of the form StateName(Token), you can do:```rust
struct Token {}

enum State {
A,
B,
}

struct StateMachine {
state: State,
token: Token,
}

impl StateMachine {
fn transition(&mut self) {
self.state = match self.state {
State::A => State::B,
State::B => State::A,
}
}
}

#

If there are 0 or 1 tokens, token: Option<Token>,.