Skip to content

Instantly share code, notes, and snippets.

@e3prom
Last active February 20, 2019 15:36
Show Gist options
  • Save e3prom/c1460571600de93a35079ff68d370fd3 to your computer and use it in GitHub Desktop.
Save e3prom/c1460571600de93a35079ff68d370fd3 to your computer and use it in GitHub Desktop.
A simple program to demonstrate ownership and pointers (de-)references with Rust.
fn main() {
// simple memory tests with integers (usually stored onto the stack).
// integers Types have the Copy Traits, therefore old variables are still
// available and can be referenced.
let x = 1;
let y = x;
println!("x stored at {:p} is {}, y stored at {:p} is {}", &x, x, &y, y);
// tests with immutable strings.
let s1 = "immutable";
println!("string s1 stored at {:p} (stack:{:p}) is \"{}\"", &*s1, &s1, s1);
let s2 = s1; // s1 is now invalidated (no shallow copy)
println!("string s2 stored at {:p} (stack:{:p}) is \"{}\"", &*s2, &s2, s2);
// other tests, this time with mutable strings.
let mut s3 = String::from("secret");
s3.push_str(" string");
println!("string s3 stored at {:p} (stack:{:p}) is \"{}\"", &*s3, &s3, s3);
let s4 = s3; // s3 is now invalidated (no shallow copy)
println!("string s4 stored at {:p} (stack:{:p}) is \"{}\"", &*s4, &s4, s4);
// example of pass by reference.
let s5 = String::from("idontpullstringforyou");
let s5_len = string_length(&s5);
println!("string s5 stored at {:p} is \"{}\" (size: {})", &*s5, s5, s5_len);
}
// this function get (borrow) a String and return its size.
fn string_length(s: &String) -> usize {
println!("calculating size of string stored at {:p} (as referenced by {:p})", &**s, &*s);
s.len()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment