Rust with diagram: Ownership 3 - Data interaction with Clone

Diego BarrancoDiego Barranco
2 min read

Before delve deeper into how data interacts in memory with clone, you should know about Rust's memory apporach and check Data interaction with Clone article.

Variables & Data interaction with Clone

Variables and data interaction with clone means that data stored at the pointer address (in the Heap) is copied each time that is assigned to another variable.

let s1 = String::from("hello"); // 1. Assign "hello" into the Heap
let s2 = s1.clone(); // 2. Copy s1 to s2

println!("s1 = {}, s2 = {}", s1, s2); // 3. Rust can access s1 because s1 is independent of s2

Let's see what's happening under the hood:

1. Assign "hello" into the Heap

"s1" group (ptr, len, capacity) is stored in the Stack where:

  • "ptr" is the pointer address where data "hello" is stored in the Heap (as shown in the right table).

  • "len" is how much memory (in bytes) are currently using.

  • "capacity" indicates the total amount of memory (in bytes) that the Stack group "s1" (shown in the table above) is received from the allocator.

2. Copy s1 to s2

  • Stack data (s1) is copied (pointer, length and capacity), just like Heap data is copied too, not reassigned.

  • s1 and s2 are independent.

3. Rust can access s1 because s1 is independent of s2

Unlike with variables and data interaction with move, when you clone data in Rust, it isn't invalidated. Therefore, when Rust can access to it. Does this mean that you can always use it? No, interaction with move is better way to handle memory than copy. It's you responsibility detect when you can use move and when you cannot.

Next article

Once we see how variables & data interacting with clone, i will summarize how variables and data interacting on Stack with Stack-Only Data: Copy

Read next article


I wish that this content helps you to learn Rust while i do it. If you have doubts, suggestions or you see errors, please don't be shy and comment on them. The goal of this content is learn together!

References:

0
Subscribe to my newsletter

Read articles from Diego Barranco directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Diego Barranco
Diego Barranco