When writing data structures or helpers (like iterators), I find myself writing almost identical code for
&mut T in straightforward cases (when wrapping another data structure, for example) and I find the current state to be a bit dissatisfying.
I’ve asked related questions about it before —
- one based on implementing basic data structures (inspired by Gankro’s too-many-linked-lists tutorial) with a lot of near-repetitions, and
- another about avoiding unnecessary monomorphizations with an interesting answer by brson on his attempts to reduce code bloat when rust code would result in identical machine code.
So avoiding duplication has two aspects: (1) DRYing out the code (first question post above; macros can help with that), and (2) resulting in exactly one binary monomorphization (@brson’s abandoned approach in the second post above might help with that).
The first post mentions a straightforward doubly-linked-list implementation, with
Iterimplementation using this helper, and
IterMutimplementation using this identical-looking helper
(and other kinds of near-duplication as well, but I’d like to focus on mutability.)
In the cases where it is possible, I would just love to just define
IterMut with all its more stringent constraints and tell the compiler to allow it to be interpreted as an
Iter as well because its implementation is (almost) identical. Essentially, what I want is to parametrize
&mut, write the code once, and generate identical code – kinda what we do when parametrizing by lifetime.
(Implicit in my assumption is that
&mut T have the same binary representation, but I may be very, very wrong since transmuting the former to the latter is undefined behavior, though it’s not obvious to me whether that’s due to correctness checking or something else in the binary.)
Is there some reason that this should not be possible?