r/rustjerk • • Oct 14 '26

Rust devs hate this one simple trick

Post image
409 Upvotes

39 comments sorted by

View all comments

Show parent comment

21

u/pragmojo Oct 14 '26

Rust's borrow checker disallows holding two mutable pointers to the same address at the same time. This code uses unsafe blocks to get two mutable pointers to the same address at the same time.

6

u/letmehaveanameyoudum Oct 14 '26

thank you for breaking my mind

2

u/schungx Oct 14 '26

If the intention is aliasing then this is a legit usage. If both self variants are supposed to point to the same thing (judging from their names) then the aliasing behavior is intended.

7

u/ChaiTRex Oct 14 '26

It's not legitimate. unsafe can be fine to use, but undefined behavior is never allowed. Aliasing a mutable reference is undefined behavior.

A workaround would be something like using mutable pointers rather than mutable references. Mutable pointers allow aliasing.