RRust By Example
beginnerOwnership

Clone and Copy

Deep copy with Clone and stack copy with Copy trait.

Clone and Copy

Deep copy with Clone and stack copy with Copy trait.

Difficulty

Beginner

Code

rust
fn main() {
    // Clone: deep copy
    let s1 = String::from("hello");
    let s2 = s1.clone();
    println!("s1 = {}, s2 = {}", s1, s2);

    // Copy: stack-only types
    let x = 5;
    let y = x;
    println!("x = {}, y = {}", x, y);
}

Explanation

This example demonstrates how to use clone and copy in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the ownership category to build a complete understanding of this topic.

More Ownership Examples