DedSec Project

E0382 — DedSec Project

Rust E0382 — trying to use a value after a move See the owner change An owned String is generally moved when passed by value. The previous binding no longer owns a valid String and must not…

Rust E0382 — trying to use a value after a move

See the owner change

An owned String is generally moved when passed by value. The previous binding no longer owns a valid String and must not be used. This compile-time check prevents use-after-move.

fn consume(text: String) -> usize { text.len() }

fn main() {
    let message = String::from("hello");
    // let size = consume(message); println!("{}", message); // E0382
    let size = consume(message.clone());
    assert_eq!(size, 5);
    assert_eq!(message, "hello");
}

Decide whether copying is actually necessary

Clone allocates another String. When the function only reads text, borrow a slice instead:

fn measure(text: &str) -> usize { text.len() }

fn check() {
    let original = String::from("hello");
    assert_eq!(measure(&original), 5);
    assert_eq!(original, "hello");
}

Lab and counterexample

Deliberately uncomment the moved-value sequence and run cargo check to observe E0382. Compare a String with an integer i32, which implements Copy. Draw a small ownership map after each statement. If the callee must own the data, redesign how the result or the data flows back; cloning everything can hide unnecessary memory costs.

Reference: https://doc.rust-lang.org/error_codes/E0382.html

Check bytes versus ownership, not just compilation

Make the borrowed version accept &str and call it twice with the same String; neither call consumes the owner. Use a string such as "é" and compare .len() (UTF-8 bytes) with .chars().count() (Unicode scalar values). This catches a separate semantic bug that the borrow checker cannot catch. A String is not Copy, while i32 is; don't infer ownership moves from the appearance of assignments alone. For a queue that must retain ownership of a submitted message, moving may be the desired API contract. Show the compiler error with a failing fixture, then test borrowing and deliberate cloning as distinct fixes.