Rust:- Compile Error – “error[E0382]: borrow of moved value”

Background

Thankfully, Rust provides ample protection against attempting to access deallocated memory.

Code

Code Snippet


fn main() 
{

    /*
        Create two variables
            a) Salutation:- Hello
            b) name:- Angie
    */
    let salutation = String::from("Hello");
    let name = String::from("Angie");
    
    /*
        Echo Contents
    */    
    println!
        (
            "1. {0}, {1}"
            , salutation
            , name
        );
    
    /*
        Drop Variable Name
    */     
    drop (name);
    
    
    /*
        Echo Contents
            Inclusive dropped variable ( name)
    */      
    println!
        (
            "2. {0}, {1}"
            , salutation
            , name
        );
    
    /*
        Clean up
    */
    drop (salutation);
    drop (name);

}

Output

Output – Text


error[E0382]: borrow of moved value: `name`
  --> main.rs:36:15
   |
10 |     let name = String::from("Angie");
   |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
...
25 |     drop (name);
   |           ---- value moved here
...
36 |             , name
   |               ^^^^ value borrowed here after move
   |
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.

Output – Image

Explanation

  1. Object Constructor
    • let name = String.from(“Angie”);
  2. Object Deallocate
    • drop(name);
  3. Attempt to use deallocated Object
        println!
        (
               "2. {0}, {1}"
             , salutation
             , name
       );
    

Remediation

  1. Please comment out the original drop statement that precedes the println!
    • from
      • drop(name);
    • to
      • //drop(name);

 

Source Code IDE

Online GDB

  1. Rust.BorrowOfMovedVariable.rs
    Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s