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
- Object Constructor
- let name = String.from(“Angie”);
- Object Deallocate
- drop(name);
- Attempt to use deallocated Object
println! ( "2. {0}, {1}" , salutation , name );
Remediation
- Please comment out the original drop statement that precedes the println!
- from
- drop(name);
- to
- //drop(name);
- from
Source Code IDE
Online GDB
- Rust.BorrowOfMovedVariable.rs
Link