I'm building program that will take circuit of logical gates and evaluate the circuit. I made trait for a logical gate which has methods to get the output value and register and unregister inputs (parents).
pub trait LogicalGate {
fn register_input<T: LogicalGate>(&mut self, input: &T) -> Result<(), LogicalGateError>;
}
T
in this method is any logical gate implementation.
Now, I want to implement a gate that will take one parent and return it's output. However, I have troubles storing the parent as I don't know what the type of OutputGate::parent
should be:
pub struct OutputGate<'a> {
parent: &'a dyn LogicalGate,
}
impl<'a> LogicalGate for OutputGate {
// ...
}
I want to be able to store any T: LogicalGate
there. I can't make the whole OutputGate
structure generic as I will want to be able to put multiple different structures (that all implement LogicalGate
) into one Vec
in the future.
No matter if I try &'a dyn LogicalGate
or Box<LogicalGate>
, the compiler complains that LogicalGate
cannot be made into an object, as it contains generic type parameters.
How can I make a field in a struct that can take any type T
that implements a certain trait, which contains a method that adds any type T
into the field in struct?
In C#, I would do it like this:
public interface ILogicalGate {
void RegisterInput(ILogicalGate input);
}
public class OutputGate : ILogicalGate {
private ILogicalGate parent;
public void RegisterInput(ILogicalGate input) { parent = input; }
}