I have a stylistic question. I have some types that implement a
Lookup trait (see linked example) among some other traits. The
lookup methods takes an immutable reference to
self because in this application data structures on which lookups can be performed are immutable. There is however one exception, which is a very basic lookup table that automatically generates new identifiers for strings that are not known to the lookup table. Since this is the exception rather than the rule, I don’t want to change the trait to take
&mut self, since this would cascade up to many methods that call
lookup. So, the most logical solution in this situation is to use interior mutability in this particular data type.
However, now I would like two variants of the same basic data type: one that mutates and one that doesn’t. I don’t want a setter method to change the mutability, because then immutability cannot be enforced through the type system. The most straightforward solution is to make them two separate data types. However, this would entail code duplication, since all the other implemented traits are the same.
I thought of another ‘clever’ solution where I use a type parameter to mark whether the type is mutable or immutable and use different trait implementations for the
Lookup trait based on this type parameter. Here is a simplified example:
I was wondering whether you think this is a sane solution or unnecessarily complicated.