To avoid making this an XY problem, here's some context first:
I'm writing a Rust program that manipulates math expressions. The expressions are stored in a tree, where each level is a different struct.
Here's an oversimplified example:
struct Sum(Vec<Product>);
struct Product(Vec<Factor>);
enum Factor{
Number(i64),
Variable(char),
Parens(Sum)
}
What I'm trying to do is create unique IDs for each unique instance, such that equal (as in, having the same set of children, regardless of order!) structs get the same ID.
I came up with the following:
I created a HashMap<{set of children's IDs}, ID>
, and stored an ID in each of my structs.
The problem I'm facing now is how to share the reference to the map with each struct.
- I could put the map into a
static
variable. But I feel like that would make it "too global" -- it would lock all instances of expressions into using the same map. - I could store references to the map (or
Rc
s) next to each ID, inside each struct. That sounds wasteful, and doesn't prevent "mixing" two ID systems (i.e. maps) in the same expression. - I could make an
IDManager
trait and make my structs generic over it. That feels the closest to what I imagined, but generics are generic over implementations of a trait, not instances of a struct.
Did I miss any ways to make this work? Which of my ideas would work better? Is there any way to encode this in the type system somehow? Is there a different system that would be easier to implement?