Rust Fundamentals · 15 XP Pro
Clone and Copy
Simple values such as integers, floats, bool and char live entirely on the
stack. Copying them is so cheap that Rust does it automatically: these types are
Copy, and using one never invalidates the original.
let x = 5;
let y = x; // x is copied
println!("{x} {y}"); // both still work
A String is different: it owns heap data, so assignment moves it. When you really
do want two independent owners, ask for a deep copy with .clone():
let a = String::from("hi");
let b = a.clone(); // new heap allocation with the same text
println!("{a} {b}"); // both valid
The .clone() call is visible on purpose. It can be expensive for big data, so Rust
makes you write it rather than hiding the cost. A tuple of Copy types is Copy too.
Your task
The starter for duplicate does not compile because it moves text twice. Fix it.
duplicate(text: String) -> (String, String): return two separate owned strings with the same content. Use.clone().square_and_keep(n: i32) -> (i32, i32): returnnand its square, as(n, n * n). No clone is needed sincei32is Copy.