How to handle a reference in a struct to another member in the struct

This couldn't ever work as this cite from Rustonomicon explains:

Every type must be ready for it to be blindly memcopied to somewhere else in memory. This means pure on-the-stack-but- still-movable intrusive linked lists are simply not happening in Rust (safely).

I just wish it was somewhere in more accessible place, coz deep investigation of complex parts of Rustonomicon is not something newbies read and this they make mistake #3 insanely often.

Note that Rustonomicon, basically, tells you, tantalizingly, that it is possible if you use unsafe, and, indeed, std::pin makes it possible, but… that's just not something that you want to use when you are still learning Rust.

No, it's not problem of ownership and borrowing. They could have been adjusted, probably, if the whole thing made sense. But thing about function new in the topicstarter example: it first creates Test struct and the moves it to some other place. At this point you either have introduce move constructor and allow move to be non-trivial (like C++ did) or move object to the heap (like most GC-based language do).

First approach was deemed unfeasible (it's really hard to deal with constructors since they couldn't just return error and panic in the middle of function call is just too surprising) and box everything is not something you do in a system language. If you really need that, there's pinned box, but it requires unsafe and, in general, most definitely not something you try to learn Rust with.

2 Likes