Help me understand take_mut safety


The take_mut crate uses ptr::read to “move” from a &mut T into another variable. But I’m not certain to what extent that impacts the original &mut T no longer being considered to have the T. I’m mostly thinking about what happens if T is itself a &mut. There would exist simultaneously a &mut whatever and a read-from &mut &mut whatever If usage matters, it’s possible the original was used before the take call, and the copy used during it.

I don’t understand the rules around &mut aliasing to have any idea if this is considered UB.


ptr::read() doesn’t move the value from source. I think it’s fine for the mutable aliases to exist so long as only one is “active”, which I think your case covers?

If you think of a normal mutable reference that’s reborrowed, the original still exists but compiler prevents reads/writes through it until the reborrow goes away. In your case, compiler won’t prevent it but your code should.

But, as I mentioned earlier on another thread, unsafe Rust is currently quite vague so take this with a huge grain of salt.