Typing is fun! Another crate for self-referential structs
⚓ Rust 📅 2026-04-16 👤 surdeus 👁️ 3I recently came across self-referential structs and found some execellent solutions like self_cell and yoke. They should probably be the go-to choice these days, but I still gave a thought about how these patterns should really work.
My idea is to use HRTB on the function fn derive(&Owner)->View to require this function prove that View is valid for all lifetimes of &owner, which happens to include the hypothetical 'self. We can't get the real 'self, but we know that self outlives 'a each time we get a '&a self. Then we return an instance of View with lifetime 'a. View might not be covariant over its lifetime parameter, but derive() proved that you can construct the view from 'a, a shorter lifetime of self.
It seems sound to me, so I took some time to implement it. I did not hit the wall of #![feature(fn_traits)] I originally anticipated, but I was troubled by #![feature(closure_lifetime_binder)] instead and I had to workaround it with some tricks. Here's what I got:
My personal favorite is the elegance of into_parts(). It allows you to decouple the owner and the view if and only if the view is no longer dependent on the owner, e.g. after a series of transformation via map(). This is one of the amazing side effects I got with correct typing.
When I first heard about the Japanese dish Oyakodon(親子丼), I thought it was some sort of dark joke. It's serving chicken and egg together with rice in a bowl, so they call it "parent-and-child bowl". What amuses me is that the word "Oyako" in Japanese sounds like a happy family. I bet chickens would not be thrilled about this, but I thought it made for a great name for the crate.
Any feedback would be appreciated!
11 posts - 2 participants
🏷️ Rust_feed