Skip to content

Instantly share code, notes, and snippets.

@kmdouglass
Created November 24, 2019 09:44
Show Gist options
  • Save kmdouglass/e596d0934e15f6b3a96c1eca6f6cd999 to your computer and use it in GitHub Desktop.
Save kmdouglass/e596d0934e15f6b3a96c1eca6f6cd999 to your computer and use it in GitHub Desktop.
Variable locations in memory during copy and move operations in Rust
//! Demonstrates memory layout using copy and move semantics in Rust.
//!
//! # Examples
//!
//! The memory locations that you see by running this program will almost certainly be different
//! than what is found in the examples below. The important thing to pay attention to is the memory
//! location of the variable `x`.
//!
//! ```console
//! $ cargo run --release -- --copy
//! Compiling move-vs-copy v0.1.0 (/home/kmdouglass/src/rust/move-vs-copy)
//! Finished release [optimized] target(s) in 0.00s
//! Running `target/release/move-vs-copy --copy`
//! Memory address of x: 0x7ffee579d544
//! Memory address of y: 0x7ffee579d548
//! Memory address of x: 0x7ffee579d544
//! Memory address of x: 0x7ffee579d544
//!
//! $ cargo run --release -- --move
//! Finished release [optimized] target(s) in 0.31s
//! Running `target/release/move-vs-copy --move`
//! Memory address of x: 0x7ffded2aa3d0
//! Memory address of y: 0x7ffded2aa3f0
//! Memory address of x: 0x7ffded2aa3d0
//! ```
use std::env;
use std::process::exit;
fn copy_semantics() {
let mut x = 42;
println!("Memory address of x: {:p}", &x);
// Move occurs here
let y = x;
println!("Memory address of y: {:p}", &y);
// Printing the memory address of x is not an error because its value was copied.
println!("Memory address of x: {:p}", &x);
// Assign new integer to x
x = 0;
println!("Memory address of x: {:p}", &x);
}
fn move_semantics() {
let mut x = String::from("foo");
println!("Memory address of x: {:p}", &x);
// Move occurs here
let y = x;
println!("Memory address of y: {:p}", &y);
// Printing the memory address of x is an error because its value was moved.
// println!("Memory address of x: {:p}", &x)
// Assign new string to x
x = String::from("bar");
println!("Memory address of x: {:p}", &x);
}
fn print_help() {
println!("Possible options: --copy, --move");
}
fn main() {
let args: Vec<String> = env::args().collect();
match args[1].as_ref() {
"--copy" => copy_semantics(),
"--move" => move_semantics(),
"--help" => {
print_help();
exit(0);
}
_ => {
print_help();
exit(1);
}
}
}
@malongshuai
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment