3 ms·
Self-referential structs work fine in Rust and always have. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4ce733c6c52318c2105d2040057
by Arnavion 3y ago
Self-referential structs work fine in Rust and always have.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4ce733c6c52318c2105d20400575fe2f https://play.rust-lang.org/?version=stable&mode=debug&editio...
The compiler will correctly prevent you from moving the value. (Try adding `drop(foo);` at the end.)
The other way to have a struct that requires mutation to move in and out of self-referential-ness (as `async {}` needs, for example) can be achieved with `unsafe` and `Pin::new_unchecked`.
- orlp 3y ago> Self-referential structs work fine in Rust and always have. They 'work fine' in that the Rust compiler will let you create one and then never let you move it or access the whole object mutably again while it is self-referential. They don't 'work fine' as in being first-class objects in the language that work as any other object. For what it's worth, I think Rust made the right choice in not allowing custom move constructors that would enable first-class self-referential types.
- trws 3y agoI agree they made the right decision not to add custom move constructors, potentially throwing move constructors and unmovable types make life very, very difficult for certain things in c++. That said, an annotation on a field that it either always references part of the parent or may reference part of the parent (or better a defined range or expression from the parent) could provide enough information for an automatically generated move constructor to correctly update the parent referencing pointer or reference. It’s entirely machinable, we had to do a version of this for the OpenMP offload memory model. It’s not the simplest thing, but updating references based on known offsets from known bases isn’t itself all that hard. Getting the syntax for the user to provide enough information to do it to be ergonomic however, that’s hard.