String Addition Moves The Left Operand

Watch the plus operator move the left String into the result, and switch to format! or push_str when the original value must stay usable.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    let base = String::from("report");
    let suffix = String::from(".txt");

    // + 消费(move)左操作数:base 的所有权进入拼接结果
    let filename = base + &suffix;
    println!("filename: {filename}");

    // 要继续使用原值,改用只借用的 format!
    let left = String::from("report");
    let kept = format!("{left}{suffix}");
    println!("left still usable: {left}");
    println!("kept: {kept}");

    // push_str 就地追加:只借 self,不发生所有权转移
    let mut log = String::from("start");
    log.push_str(" -> done");
    println!("log: {log}");
}

How it works

String Addition Moves The Left Operand keeps everything in the function main.

Using it

The demo output is labeled (filename:, left still usable:, kept:), so every printed line maps back to its originating operation.

Key statements

let kept = format!("{left}{suffix}");
let mut log = String::from("start");
let base = String::from("report");

Interactive Tools for This Topic

FAQ

What does String Addition Moves The Left Operand print when run?
Execute the whole file; each printed line is prefixed with a label like `filename:`, `left still usable:`, `kept:`.