Background:
I am trying to implement a simple Virtual Machine in Rust. For now, I am working on a "RegisterBank" which supports space for Strings and Integers. The RegisterBank struct looks the following:
pub struct RegisterBank {
int_registers: Vec<i32>,
str_registers: Vec<String>,
}
So it is just a simple collection of two vectors.
Previous work:
When I tried to implement the "load" and "store" functions, there was the choice between two seperate functions
pub fn load_int(...) { ... }
pub fn load_str(...) { ... }
and pattern matching (which I wanted to learn anyway)
pub fn load(self, register: SomeMatchableType) {
match register { ... }
}
Because having one function for two very similar tasks seemed good, I tried something like this:
enum OperandType {
Number(i32),
Word(String),
}
and then have a function like pub fn load(self, register: OperandType) which matches register and returns either a String (or &str, whatever) or an integer depending on its operand type.
Problem:
Currently the implementation is stuck on two seperate functions (for i32 and String) and this is working fine. Since I have managed to do this for fn store(&mut self, register: usize, value: OperandType) this should be possible for fn load(self, register: ???) as well. My biggest problem is to design such a function that combines both tasks into one pattern match depending on the OperandType enum (or maybe something else if someone has a clever idea).
Basically, the solution should do:
- Decide which register (int_registers or str_register) to choose based on input parameter
- Get the content of the register
- Return it
enum RegisterType { Number(usize), Word(usize) }- AdrianOperandTypeto justOperand- Adrian