Skip to content

Instantly share code, notes, and snippets.

@floooh
Last active June 26, 2016 18:34
Show Gist options
  • Save floooh/1f2d3d11ae327beba29f565ffb5429fe to your computer and use it in GitHub Desktop.
Save floooh/1f2d3d11ae327beba29f565ffb5429fe to your computer and use it in GitHub Desktop.
This is so far the only really annoying thing I've encountered in Rust, and which IMHO doesn't
make sense (and I guess this is this known issue: https://github.com/rust-lang/rust/issues/29975).
I have a simple struct with the Z80 CPU emulator state, most of the functions in the impl block need
to modify the content of the struct(for instance in the case of the inc8() method, set
status flags):
struct CPU {
pub reg : [i64, NUM_REGS];
...
}
impl CPU {
...
pub fn inc8(&mut self, val: i64) -> i64 {
let res = ... // compute new value
self.reg[F] = ...; // update status flags
res // return result
}
...
So, inc8() takes a value, and returns an incremented value, and updates the internal
status flag register.
From another "&mut self method" I would expect that I could do the following:
self.reg[B] = self.inc8(self.reg[B]);
But this produces an error:
error: cannot use `self.reg[..]` because it was mutably borrowed [E0503]
Loading reg[B] into a temporary value works though, which is completely equivalent
as far as I can see:
let b = self.reg[B];
self.reg[B] = self.inc8(b);
This gets a bit annoying with slightly more complex call chains, for instance in a
load-increment-store instruction, this could be written as:
let addr = self.addr(m, d);
self.mem.w8(addr, self.inc8(self.mem.r8(addr)));
The first line computes the effective address where the value to be incremented lives. The next line
loads the value from memory, calls the inc8() method with it, and stores the result of inc8()
at the same address.
This simple code must currently written like this:
let addr = self.addr(m, d);
let v = self.mem.r8(addr);
let w = self.inc8(v);
self.mem.w8(addr, w);
A lot more noisy :/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment