How to change the outside variable in inner function

⚓ Rust    📅 2026-02-24    👤 surdeus    👁️ 1      

surdeus

I'm writing a state machine in Rust.

trait AtoI {
    fn process(&self, c: char, a: i32) -> i32;
}

fn main() {
    let mut state: Box<dyn AtoI> = Box::new(AtoISign);

    struct AtoISign;
    impl AtoI for AtoISign {
        fn process(&self, c: char, a: i32) -> i32 {
            state = Box::new(AtoIPos);
            return 0;
        }
    }

    struct AtoIPos;
    impl AtoI for AtoIPos {
        fn process(&self, c: char, a: i32) -> i32 {
            return 0;
        }
    }

    state.process('0', 0);
}

A state is a struct which implements trait AtoI. In some conditions, I need to change the value of the ourside variable state in function process. But rust compiler complains:

error[E0434]: can't capture dynamic environment in a fn item
  --> src/main.rs:11:13
   |
11 |             state = Box::new(AtoIPos);
   |             ^^^^^
   |
   = help: use the `|| { ... }` closure form instead

Question: How could I change the state variable in the process function?

Something I tried:

  1. Pass a closure parameter to function process. It complains: "AtoI can't be dyn since it has a function of generic parameter".
  2. Write a closure inside function process and capture state. It fails because closure can only capture the variables of the same scope.
  3. Pass state in the parameter of function process. It complains: "use mutable borrowed variable with immutable borrowed variable".

9 posts - 2 participants

Read full topic

🏷️ Rust_feed