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
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
clone() deep copies. Copy types (integers, bools) are automatically copied.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the ownership category to build a complete understanding of this topic.