From 3f5d729285f8ad23f0bc4e993a7537f5b71c35ba Mon Sep 17 00:00:00 2001 From: sgoudham Date: Fri, 11 Feb 2022 19:29:42 +0000 Subject: [PATCH] Add Smart Pointers --- book/smart_pointers/Cargo.toml | 8 ++++++++ book/smart_pointers/src/main.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 book/smart_pointers/Cargo.toml create mode 100644 book/smart_pointers/src/main.rs diff --git a/book/smart_pointers/Cargo.toml b/book/smart_pointers/Cargo.toml new file mode 100644 index 0000000..54a2397 --- /dev/null +++ b/book/smart_pointers/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "smart_pointers" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/book/smart_pointers/src/main.rs b/book/smart_pointers/src/main.rs new file mode 100644 index 0000000..f794f3b --- /dev/null +++ b/book/smart_pointers/src/main.rs @@ -0,0 +1,33 @@ +use std::ops::Deref; + +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +impl Deref for MyBox { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +fn hello(name: &str) { + println!("Hello, {}!", name); +} + +fn main() { + let x = 5; + let y = MyBox::new(x); + + assert_eq!(5, x); + assert_eq!(5, *y); + + let m = MyBox::new("Rust"); + hello(&m); + get_name(); +} \ No newline at end of file