I'm trying to build a small TCL interpreter and I'm stuck with a borrowing problem:
error[E0502]: cannot borrow `*self` as mutable because `self.commands` is also borrowed as immutable
--> src/lib.rs:97:13
|
96 | let cmd = &self.commands.get(cmd_name).unwrap();
| ------------- immutable borrow occurs here
97 | cmd(self, params)
| ^^^^ mutable borrow occurs here
98 | }
| - immutable borrow ends here
Here, self
is the interpreter context which, for example, stores all the available commands
in a hash map. The first line retrieves the command we want to execute from that hash map and the second line executes it. I want to pass the context into the command so it could, for example, add more commands. This inherently creates some aliasing, since the command has a self
reference and the context which also references that. I'm not sure how to resolve that conflict.
- Make mutable borrow immutable? Then I cannot add more commands.
- Create a copy/clone? I don't know how. It seems to be tricky because a closure is involved?
- The
unsafe
cop out? It might be reasonable, since in contrast to the compiler, I know that the closure object is actually immutable even if the whole context is not. Maybe there is a safer way to tell the compiler that?