Self Referential Structs in Rust (Part 1)
TL;DR
Use Pin<Box<T>> for the held value (here, Me).
Mark Me as unpinnable by setting a field as std::marker::PhantomPinned.
Eg, _pinned: std::marker::PhantomPinned.
Use Rc<RefCell<H>> for holder, (here, Holder) and store Me as raw
pointers.
Eg, me...
arunanshub.hashnode.dev13 min read
Good post! Made me understand pinning ^^
I only wish rust had a way to force immutability on a boxed value together with a lifetime. I mean something like this:
struct URI<'a> { raw: String<'a>, pub protocol: &'a str, }Assuming
protocolpoints to a substring ofraw, my understanding is, that this would be entirely unproblematic unless someone mutatesraw. Since it's not public and none of the implemented methods for it, mutate it, is there any example of where this could lead to a dangling reference?And with the lifetime on
String, rust could ensure that, whilerawmay still be changed, the previous string would still have to be available for at least'a, ensuring that it won't breakprotocol.I'm never sure whether I should be happy that rust "thinks of everything" and won't let me write potentially problematic code, or whether I just want to tell rust "trust me bro", because it doesn't apply to the actual code…