In this lesson, we explore the interaction between variables and data cloning in Rust. Rust employs a move mechanism to safeguard memory by transferring ownership between variables. However, situations arise where you need to retain access to the original data while creating an independent duplicate. This is where the clone trait becomes essential. Rust’s clone trait explicitly generates deep copies of data. It is particularly useful for duplicating heap-allocated resources that cannot be managed through a simple bitwise copy. In contrast, the copy trait is reserved for types stored entirely on the stack—such as integers, floats, and simple tuples—that support inexpensive shallow copies.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.

- The copy trait is used for types that do not manage heap memory (e.g., integer types).
- The clone trait is essential for types that allocate memory on the heap or hold other resources, ensuring each copy has its own independent allocation.

Practical Examples
Consider the following examples to understand the difference between copying and cloning in Rust. The typei32 implements the Copy trait, so its value is automatically copied during assignments. On the other hand, a String requires an explicit call to clone to create an independent copy.
x (of type i32) is effortlessly copied, allowing both x and y to be used independently. For the String type, invoking s1.clone() explicitly creates an independent duplicate, ensuring that both s1 and s2 point to different heap allocations.
When you create a string using String::from, memory is allocated on the heap. The string consists of a pointer, its length, and its capacity. Invoking clone on a string allocates new memory and copies the content from the original string. Thus, the new string, s2, has its own pointer, length, and capacity.
