Self-referential struct with help of Pin?

Is it possible to solve the problem with help of Pin?

Note: this code requires byte-slice-cast = "1.2.0"

The unsafe code required to write your self-referential struct would not involve Pin.

1 Like

Pin doesn't let you do stuff that would require unsafe, quite the opposite, it is only useful when you're already writing unsafe code and you want to expose an API that requires your type to be pinned.

Moreover that code doesn't even need pin because the self-referential part lives on the heap, so it's already pinned. It has however a big problem with the public fields because they allow its owner to have mutable access to the heap box while a shared reference exists (the other field). Moreover that reference has a lifetime that's always longer than the Context itself, so it being public allows someone to keep it after the Context has been dropped and the heap allocation freed.


What about hiding those fields as non-public?

That obviously solves the problem, but of course it won't allow you to do anything with that struct. You're gonna need to somehow expose them somewhere, so you'll need to checker whether those uses are sound or not. Note that you'll need to check any method that directly use those fields, even if they don't have any unsafe.

1 Like

Thanks. I can expose just methods and refs. What do you think about such solution?

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.