diff --git a/2024/rust_mem_model/Cargo.lock b/2024/rust_mem_model/Cargo.lock new file mode 100644 index 00000000..36bf1bf1 --- /dev/null +++ b/2024/rust_mem_model/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "rust_mem_model" +version = "0.1.0" diff --git a/2024/rust_mem_model/Cargo.toml b/2024/rust_mem_model/Cargo.toml new file mode 100644 index 00000000..8100d28c --- /dev/null +++ b/2024/rust_mem_model/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "rust_mem_model" +version = "0.1.0" +edition = "2021" + + diff --git a/2024/rust_mem_model/src/step_1.rs b/2024/rust_mem_model/src/step_1.rs new file mode 100644 index 00000000..a3ee3b4e --- /dev/null +++ b/2024/rust_mem_model/src/step_1.rs @@ -0,0 +1,40 @@ + +// fn main() { +// let s1 = String::from("hello"); +// let s2 = s1; +// println!("{}, world!", s1); +// } + +// fn main() { +// let s1 = String::from("hello"); +// let s2 = &s1; +// println!("{}, world!", s2); +// } + +// fn main() { +// let mut s1 = String::from("hello"); +// let s2 = &mut s1; +// s2.push_str(", world!"); +// println!("{}", s1); +// } + +// fn main() { +// let mut s1 = String::from("hello"); +// let s2 = &mut s1; +// let s3 = &mut s1; +// s2.push_str(", world!"); +// println!("{}", s1); +// } +// + +// fn main() { +// let s1 = String::from("hello"); +// let s2 = s1.clone(); +// println!("{}, world!", s1); +// } + +// fn main() { +// let s1 = String::from("hello, world!"); +// let s2 = &s1[0..5]; +// println!("{}", s2); +// } \ No newline at end of file diff --git a/2024/rust_mem_model/src/step_2.rs b/2024/rust_mem_model/src/step_2.rs new file mode 100644 index 00000000..27ca19d0 --- /dev/null +++ b/2024/rust_mem_model/src/step_2.rs @@ -0,0 +1,17 @@ + +// fn main() { +// // stack allocation +// let x = 5; +// let y = x; +// +// println!("x = {}, y = {}", x, y); +// } + +// fn main() { +// // heap allocation +// let s1 = String::from("hello"); +// let s2 = s1; +// +// println!("{}, world!", s1); +// } + diff --git a/2024/rust_mem_model/src/step_3.rs b/2024/rust_mem_model/src/step_3.rs new file mode 100644 index 00000000..27dc8460 --- /dev/null +++ b/2024/rust_mem_model/src/step_3.rs @@ -0,0 +1,20 @@ +mod main; + +fn same_lifetime<'a>(s: &'a str, start: usize, end: usize) -> &'a str { + &s[start..end] +} + +fn equal_lifetimes<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + let s1 = String::from("hello, world!"); + let s2 = same_lifetime(s1.as_str(), 0, 5); + let result = equal_lifetimes(s1.as_str(), s2); + println!("The longest string is {}", result); +}