Arjun
Arjun

Reputation: 3793

Can we reimplement Move semantics in rust just like Clone?

Can we tinker with move semantics in rust.

Maybe reimplement Move behavior just like Clone?

Or at least attach pre or post move hook to execute custom logic?

links to official rust docs would be appreciated.

From the internal language redesign proposal thread Idea: Limited custom move semantics through explicitly specified relocations it seems it's not present.

but I want make sure there no way of achieving it.

Upvotes: 0

Views: 134

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70900

Not just there is no such way, and not just this is a good thing (IMO), changing that is basically impossible now, and all proposal that attempted to do that were opt-in rather than opt-out (that is, your generic type should declare support in non-bitwise moves, or it will not support them. Basically some kind of opt-out trait ?Move). That means that a lot of things won't support them, at least in the ecosystem if not in std too.

This is for a very simple reason: lots of unsafe code relies on moves to be bitwise. If a move can execute user code, that also means it can panic, and now unsafe code has to defend against that. Or they can leave the object in invalid state even if it wasn't before. Basically, they can do anything, and this anything can mean anything to unsafe code. And anything possible in unsafe code means undefined behavior. So no existing unsafe code will be able to live with this moves, which means that no code at all will be able to and each type will have to declare if it supports them.

Not to mention the optimization benefits or that it's much easier to reason about bitwise move.

I don't think there was ever a RFC to do that, although I may not be aware (there was a RFC for ?Move, but it was replaced by Pin).

If you need a way to customize moves, you don't want moves. Use Clone or some other trait.

Upvotes: 1

Related Questions