Type expansion with recursive function

Minimal example playground link

I am trying to implement a serialization function for a recursive tree data structure. The function takes in a Write object and passes it by mutable reference to the recursive calls. Unfortunately, this recursively expands the Write type, attempting to instantiate generic instances of the function for each new recursion. This is roughly visualized below.

instantiate encode<W>
-> instantiate encode<&mut W>
-> instantiate encode<&mut &mut W>
-> instantiate encode<&mut &mut &mut W>
-> ... etc

Is there a good idiomatic way to work around this issue? Ideally I would like to keep it recursive and generic, as I think that is the most intuitive way to express this feature.

Just take &mut impl Write instead of impl Write: playground. (You might need to insert explicit &mut *o reborrows depending on the actual shape of your code.)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.