Copy Clone And Move Semantics

Separate Copy types that duplicate on assignment from types that transfer ownership, and reach for clone only when a real duplicate is needed.

RustData Integrity

Code

rustsnippet
26 lines
fn consume(message: String) {
    println!("consumed: {}", message);
}

fn main() {
    // Copy 类型:赋值按位复制,原值依旧可用
    let a: i32 = 42;
    let b = a;
    println!("copy semantics: a={} b={}", a, b);

    // 元组若所有元素都实现 Copy,整体也是 Copy
    let pair = (1, "x");
    let pair_copy = pair;
    println!("tuple copied: {:?}", pair_copy);

    // move 语义:String 赋值转移所有权,原绑定随后失效
    let owner = String::from("payload");
    let moved = owner;
    consume(moved);

    // 确需两份独立数据时才显式 clone:深拷贝,两值此后互不影响
    let original = String::from("keep");
    let duplicate = original.clone();
    consume(original);
    println!("duplicate survives: {}", duplicate);
}

What the code does

Two functions carry it: consume takes a String by value and prints it, while main stages the Copy case (i32, then the tuple), the move case, and the explicit original.clone().

Using it

fn consume(message: String) takes its argument by value — the call is exactly what retires the moved binding.

Every stage prints its own label — consumed:, copy semantics: a=, tuple copied: — so the line where a stays usable after assignment sits right next to the line where the moved String is consumed.

The demo flow inside main is consume — run the file to see it end to end.

Key statements

fn consume(message: String) {
println!("consumed: {}", message);
}

Interactive Tools for This Topic

FAQ

What does Copy Clone And Move Semantics print when run?
Execute the whole file; each printed line is prefixed with a label like `consumed:`, `copy semantics: a=`, `tuple copied:`.