Skip to content

Instantly share code, notes, and snippets.

@huangsam
Last active April 26, 2020 18:51
Show Gist options
  • Save huangsam/6e451265eb0d075ac9e0969ca322d7bc to your computer and use it in GitHub Desktop.
Save huangsam/6e451265eb0d075ac9e0969ca322d7bc to your computer and use it in GitHub Desktop.
Show how ownership in Rust works
/// See link more details:
/// https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
fn main() {
// String is made up of the following:
// - pointer to string contents
// - length
// - capacity
let s1 = String::from("hello");
// immutable transfer from s1 to s2
let s2 = s1;
// mutable transfer from s2 to s3
let mut s3 = s2;
s3.push_str(", world!");
// immutable transfer from s3 to s4
let s4 = s3;
// println!("{}", s3);
// println!("{}", s2);
// println!("{}", s1);
// immutable borrow of s4 by fn
let s4_len = calculate_length(&s4);
println!("s4 => '{}'", s4);
println!("length(s4) => {}", s4_len);
// s4 is still an owner after clone
let mut s5 = s4.clone();
// s4 and s5 are not the same
s5.push_str(" hasta la vista.");
println!("s4 => '{}', s5 => '{}'", s4, s5);
// immutable transfer from s5 to fn
let s5_len = calculate_length_borrow(s5);
println!("length(s5) => {}", s5_len);
// println!("s5 => {}", s5);
}
/// Calculate length with reference
fn calculate_length(s: &String) -> usize {
s.len()
}
/// Calculate length with borrowing
fn calculate_length_borrow(s: String) -> usize {
s.len()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment