Our final freshman year coding project was creating a logic simulator (the basic NOT, AND, OR, etc. gates) in C++. I decided I would rewrite it in Rust for some hands-on experience.
Right now, I'm working on creating an in-memory representation of the circuit from the input. I have a Simulation struct which holds the wires and gates:
pub struct Simulation {
wires: Vec<Wire>,
gates: Vec<Gate>,
}
This is the centralized spot where I store these, however, I need to access the wires and gates in other parts of my code.
Currently, I'm using static references in the Wire and Gate structs (I'm not sure I need a static lifetime but that's another topic). However, I'm getting errors when I try to return references.
impl Simulation {
pub fn get_wire(&self, num: usize) -> Result<&'static Wire, &str> {
for wire in &self.wires {
if wire.number == num {
// Error: lifetime may not live long enough
// returning this value requires that `'1` must outlive `'static`
return Ok(wire);
}
}
Err("No wire found")
}
}
Since the Simulation struct will stick around for the whole program, there shouldn't be any issues with a reference to a wire or gate outliving the simulation. I've read the book about references, but there weren't any examples close this complex.
What am I missing? How can I use references in the rest of my program? Do I need to put it in an Rc<>?
I've tried a few different ways to access the wires, but each gives similar errors.