Rust with diagrams: Ownership 4 - Stack-Only data: Copy

Rust with diagrams: Ownership 4 - Stack-Only data: Copy

Rust documentation with diagrams to fast learn and remember. Let's learn together in Chapter 4.1.

Before delve deeper into how data interacts in memory with stack-only, you should know about Rust's memory apporach and i recommend read Data interaction with Move and Data interaction with Clone.

STACK-ONLY DATA: COPY

In the "Rust's memory approach" article, we discuss how, if size and type of data are known, the better way to store this data is in the Stack. Copy data from Stack to Stack is ultra-fast and has good performance, therefore, Rusts allows it.

Let's to see an example:

let x = 5; // 1. Data is assgned into the Stack
let y = x; // 2. x is copied to y in the Stack

println!("x = {}, y = {}", x, y); // 3. x and y extist and they are accessible

Rust can implement different traits for simple scalar values. In the above example, Rust can implement the "Copy" trait to the integer type 5. The "Copy" trait can be implemented to any group of simple scalar values that do not require allocation. These are all the types that can implement the "Copy trait:

  • All the integer types, such as u32.

  • The Boolean type, bool, with values true and false.

  • All the floating-point types such as f64.

  • The character type, char.

  • Tuples, if they only contain types that also implement Copy. For example, (i32, i32) implements "Copy" trait, but (i32, String) does not.

Conclusion

After understanding how variables interact in the Stack and in the Heap, we have enough knowledge to handle memory correctly when writing Rust programs.

We will prefer "Stack-Only data: Copy" whenever possible. if its not possible, we will use "Variables & data interacting with move", and finally, we should try to avoid" Variables & data interaction with clone" as much as possible.

Next article

Once at this point of Rust Ownership knowledge, i will talk about Ownership rules, Scope and see how Ownership works in functions.

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: