Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Clone for copying on the heap, while Copy for copying on the stack in Rust?

Tags:

rust

As the title says, will I be correct to say that Clone for copying on the heap, while Copy for copying on the stack in Rust?

This is basically what this article here says, but I have doubts over its correctness.

like image 412
Finlay Weber Avatar asked Oct 18 '25 21:10

Finlay Weber


1 Answers

Copying vs cloning do not equate to stack vs heap. Copy and Clone are traits which are properties of the type, not properties on where the value lies. They are more closely tied with ownership than memory region.

Consider this example where integers are stored on the heap (via Vec) and I copy from one element to another. This uses Copy (because there is no explicit .clone()) and yet both the source and destination are on the heap:

let mut v = vec![0i32; 10];
v[0] = v[1];

Consider this example where a RefCell is stored on the stack, and uses Clone to get another of the same. Both elements are on the stack and yet I must use .clone() because RefCell does not implement Copy. A RefCell doesn't use any heap allocations either:

let rc1 = RefCell::new(...);
let rc2 = rc1.clone();

A type implementing Copy simply means that it can be bitwise-copied from one memory location to another and have both instances be equally valid.

What is important for comparing Copy and Clone is if there is additional meaning that needs to be applied when the type is created or destroyed beyond the in-place data it holds. Having ownership over heap-allocated memory is one of those cases, since you would need to de-allocate that memory when the owner is destroyed. Keeping additional book-keeping records, as a RefCell does would also disqualify it from implementing Copy since a simple bitwise-copy of the data would yield inconsistent or unusable results. Managing an external resource like an file handle is another case since you must coordinate with the OS to open() and close() the file explicitly.

like image 165
kmdreko Avatar answered Oct 20 '25 16:10

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!