Finlay Weber
Finlay Weber

Reputation: 4153

What is memcpy in the differfence between Copy and Clone in Rust?

I am trying to understand the difference between Clone and Copy in Rust. And Googling the answer I see seems to boil down to: Clone is designed for arbitrary duplications, while Copy represents values that can be safely duplicated via memcpy.

The problem with all these answers is all the reference to memcpy assumes the reader knows what memcpy

But for someone like me who is not sure about memcpy since I have no experience with C/C++ not sure how this helps explain difference between Copy and Clone.

Can someone help explain what memcpy is, and specifically how mentioning it, differentiates between Copy and Clone?.

Upvotes: 1

Views: 835

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

memcpy is a low-level system function that copies byte buffers. In pseudocode, memcpy does the following:

memcpy(to, from, size):
  for i from 0 to size:
    to[i] = from[i]

That is, it’s really a simple, element-wise copy of bytes from one memory location to another of a fixed length. But it’s implemented very efficiently. If a type is memcpy-able, it means that its memory representation contains no logic which depends on its memory location. That is, an object is still valid once it has been duplicated or moved to a different memory address.

This is true for types such as i32 or f64. But it is not true e.g. for vectors, because a vector is usually implemented as a size, a capacity and a pointer to another buffer. If we copied a vector via memcpy, this pointer in the new object would now still point to the old object’s buffer. That’s why i32 etc. implement Copy, but std::vec::Vec does not.

Upvotes: 5

Related Questions