rust ownership_error ai_generated true

error[E0382]: borrow of moved value

ID: rust/e0382-borrow-moved-value

Also available as: JSON · Markdown
85%Fix Rate
88%Confidence
245Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Value was moved to a new owner and can no longer be used. Core Rust ownership concept.

generic

Workarounds

  1. 90% success Use references (&T or &mut T) instead of moving ownership
    fn process(data: &Vec<i32>) instead of fn process(data: Vec<i32>)

    Sources: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html

  2. 85% success Use .clone() if the type implements Clone and you need multiple owners
    let data = vec![1, 2, 3];
    let data_copy = data.clone();  // explicit clone
    process(data);      // moves data
    analyze(data_copy); // uses the clone

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

  3. 90% success Use references (&T or &mut T) instead of moving ownership
    // Instead of taking ownership:
    fn process(data: &[i32]) {  // borrow with &
        println!("{:?}", data);
    }
    let data = vec![1, 2, 3];
    process(&data);  // borrow, don't move
    println!("{:?}", data);  // data still usable

    Sources: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html

Dead Ends

Common approaches that don't work:

  1. Clone everything to avoid moves 65% fail

    Unnecessary allocations, poor performance, doesn't teach ownership

  2. Use unsafe to bypass borrow checker 92% fail

    Undefined behavior risk, completely wrong approach

Error Chain

Leads to:
Preceded by: