How can we teach people about self-referential types?

I agree that as a community we could do better with these kinds of questions. Especially because self-referencing objects are possible in safe Rust; in fact, sometimes they're pretty easy to make, and the compiler helps you avoid breaking things with them... which is of course where the problems come in, because many things you might want to do with a self-referential struct actually do break it.

On the other hand, these questions are almost always rooted in an XY problem. Most code snippets that people post don't really demonstrate a need for self-reference at all. But because people also don't post their functional requirements that led them (however erroneously) to their current design, it's not like one can backtrack to the point where they started going wrong and correct the design.

Data structure design is software engineering, and you can't do it without a firm grasp of what problem is being solved and which constraints must be met. When someone posts "I have this design, how do I make it work?" with zero functional requirements and some code that clearly won't work, there's often not much to say beyond "You need to go back to the drawing board."

That said, obviously many other languages don't have such issues with self-reference. Why is that? In C++ you have move and copy constructors to "fix up" references inside structs when moved - that's one answer. In Java every object is reference counted; that's another. Both of these approaches are possible to write manually in (even mostly safe) Rust, so if you've really painted yourself into a corner and self-referencing is actually the only solution, you can write it, it's just going to be massively inconvenient.

How do you avoid that? I don't think there are any secrets to good design, and there's no magic technique that will turn every self-referential pumpkin into an elegant data-oriented carriage. You just need to know your functional requirements and pick a design that plays to the strengths of your tools. Designing software in Rust is different than designing software in Java; not all the same techniques apply.

24 Likes