3 ms·
Let's assume for a moment self-referential references were allowed. Let's further say we have such a struct containing self-referential references and we move i
by DasIch 5y ago
Let's assume for a moment self-referential references were allowed. Let's further say we have such a struct containing self-referential references and we move it.
Moving actually moves things in memory, including the thing those references reference. This means the references now point at the old and now incorrect location. Accessing them would trigger undefined behavior.
Self-referencing is only acceptable, if the struct is guaranteed not to move. Rust does provide a mechanism to provide such a guarantee with std::pin but outside of async code, you probably don't want to be using it.
std::pin: https://doc.rust-lang.org/std/pin/index.html https://doc.rust-lang.org/std/pin/index.html
If you're curious about pinning and have a few hours to spare, https://www.youtube.com/watch?v=DkMwYxfSYNQ https://www.youtube.com/watch?v=DkMwYxfSYNQ is a great video that explains it in detail.
- edflsafoiewq 5y agoSelf-reference is allowed, but it prevents moving. fn main() { // ok let mut inp = Input { words: vec![], phrase: String::from("foo bar") }; inp.words.push(&inp.phrase[0..3]); inp.words.push(&inp.phrase[4..7]); println!("{:?}", inp); // this would give "cannot move out of `inp` because it is borrowed" //let x = inp; }
- emi2k01 5y agoIt also prevents borrowing `inp` or `inp.phrase` as mutable which makes it useless for most cases.