How to change the outside variable in inner function
⚓ Rust 📅 2026-02-24 👤 surdeus 👁️ 1I'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:
- Pass a closure parameter to function
process. It complains: "AtoI can't be dyn since it has a function of generic parameter". - Write a closure inside function
processand capturestate. It fails because closure can only capture the variables of the same scope. - Pass
statein the parameter of functionprocess. It complains: "use mutable borrowed variable with immutable borrowed variable".
9 posts - 2 participants
🏷️ Rust_feed