What's difference between move and copy? When to use which?

For function parameter (not & rerference), does rust move or copy (if the variable is primitive type or with Copy trait) the variable?
For example, how about hashmap and mpsc?

And, the move is normally equal to copy in the assembly code without optimization, right?
But with optimization, the move may be passed with pointer or even in-place modification, right?

No and yes.

The Rust notion of copy and move has to do with semantics mostly and less with actual implementation. Move indicates that the variable from which it was moved is no longer valid afterwards. What that translates to assembly depends on compiler optimizations and on the exact platform. But semantically, the old variable ceases to exist after the move, the new variable takes its place. So similarly, for function calls, if you do map.insert(key, value), then both key and value cease to exist after the call.

On the other hand, Copy means that the variable doesn't cease to exist even after an assignment. So if you have a HashMap<i32, i32>, then even after map.insert(key, value), you can continue to use key and value just like you could do before. What happens in assembly again is a different story.
Thus, you can "copy" immutable references, because there is a Copy implementation for it.


So if the parameter implements Copy trait, the function would copy it, otherwise, move it, right?


1 Like

Basically: these are not two different operations. It's one and the same. Move and copy are doing the exact same thing, but move makes old object unaccesible (usually because it's complex object which refers to external entities and new copy now owns responsibility of dealing with all that while old object is no longer “alive”) while copy means that object is suitably simple thus if you do a bitwise copy of it both copy and original can be used.

1 Like