Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Created May 9, 2014 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wilfred/272cfea260b0afe0d1e0 to your computer and use it in GitHub Desktop.
Save Wilfred/272cfea260b0afe0d1e0 to your computer and use it in GitHub Desktop.
Passing immutable data to a function expecting mutable
// The Z80 is an 8-bit chip.
type Register = u8;
type ProgramCounter = u16;
type StackPointer = u16;
#[deriving(Show)]
struct CPU {
// Generic registers.
a: Register,
b: Register,
c: Register,
d: Register,
e: Register,
h: Register,
l: Register,
// Flags register.
f: Register,
// Program state.
pc: ProgramCounter,
sp: StackPointer,
// Clock.
m: Register,
t: Register,
}
fn ADDr_e (mut cpu: CPU) {
//! Add E to A, leaving result in A (ADD A, E)
cpu.a += cpu.e;
}
fn main() {
let cpu = CPU {
a: 0, b: 0, c: 0, d: 0, e: 5, h: 0,
l: 0, f: 0, pc: 0, sp: 0, m: 0, t: 0,
};
println!("Initial CPU state: {}", cpu);
ADDr_e(cpu);
println!("Final CPU state: {}", cpu);
}
$ ./emulator
Initial CPU state: CPU { a: 0, b: 0, c: 0, d: 0, e: 5, h: 0, l: 0, f: 0, pc: 0, sp: 0, m: 0, t: 0 }
Final CPU state: CPU { a: 0, b: 0, c: 0, d: 0, e: 5, h: 0, l: 0, f: 0, pc: 0, sp: 0, m: 0, t: 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment