From 0cebf66a1816e5bf3c005dff6fb17bba55c1517f Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Wed, 12 Aug 2020 16:15:01 +0800 Subject: Understand owership --- owership/src/main.rs | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 owership/src/main.rs (limited to 'owership/src/main.rs') diff --git a/owership/src/main.rs b/owership/src/main.rs new file mode 100644 index 0000000..d2bd765 --- /dev/null +++ b/owership/src/main.rs @@ -0,0 +1,139 @@ +fn main() { + /* heap data deep copy */ + let s1 = String::from("Hello"); + let s2 = s1.clone(); + + println!("s1 = {}, s2 = {}", s1, s2); + + /* stack data copy */ + let x = 5; + let y = x; + + println!("x = {}, y = {}", x, y); + + /* functions */ + let s = String::from("hello"); + + takes_owership(s); + + let x = 5; + + makes_copy(x); + + /* return values and scope */ + let s1 = gives_owership(); + + let s2 = String::from("hello"); + + let s3 = takes_and_gives_back(s2); + + /* parameters */ + let s1 = String::from("hello"); + + let (s2, len) = calculate_length(s1); + + println!("The length of '{}' is {}.", s2, len); + + /* reference(borrowing) */ + let s1 = String::from("hello"); + + let len = calculate_length_ref(&s1); + + println!("The length of '{}' is {}.", s1, len); + + /* mutable reference */ + let mut s = String::from("hello"); + + change(&mut s); + + /* mutable and immutable */ + let mut s = String::from("hello"); + + let r1 = &s; + let r2 = &s; + println!("{} and {}", r1, r2); + + let r3 = &mut s; + println!("{}", r3); + + /* slice */ + let mut s = String::from("hello world"); + + let word = first_word_index(&s); + + s.clear(); + + println!("the first word index: 0-{}", word); + + /* string slice */ + let s = String::from("hello world"); + + let hello = &s[0..5]; + let world = &s[6..11]; + + println!("{} {}", hello, world); + + /* slice first word */ + let mut s = String::from("hello world"); + + let word = first_word(&s); + + println!("the first word: {}", word); + + s.clear(); +} + +fn takes_owership(some_string: String) { + println!("{}", some_string); +} + +fn makes_copy(some_integer: i32) { + println!("{}", some_integer); +} + +fn gives_owership() -> String { + let some_string = String::from("hello"); + some_string +} + +fn takes_and_gives_back(a_string: String) -> String { + a_string +} + +fn calculate_length(s: String) -> (String, usize) { + let length = s.len(); + + (s, length) +} + +fn calculate_length_ref(s: &String) -> usize { + s.len() +} + +fn change(some_string: &mut String) { + some_string.push_str(", world!"); +} + +fn first_word_index(s: &String) -> usize { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return i; + } + } + + s.len() +} + +fn first_word(s: &String) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + + &s[..] +} -- cgit v1.2.3