summaryrefslogtreecommitdiff
path: root/smart_pointer
diff options
context:
space:
mode:
Diffstat (limited to 'smart_pointer')
-rw-r--r--smart_pointer/src/main.rs48
1 files changed, 48 insertions, 0 deletions
diff --git a/smart_pointer/src/main.rs b/smart_pointer/src/main.rs
index b19ab5f..d7ed84c 100644
--- a/smart_pointer/src/main.rs
+++ b/smart_pointer/src/main.rs
@@ -4,6 +4,24 @@ enum List {
Nil,
}
+struct MyBox<T>(T);
+
+impl<T> MyBox<T> {
+ fn new(x: T) -> MyBox<T> {
+ MyBox(x)
+ }
+}
+
+use std::ops::Deref;
+
+impl<T> Deref for MyBox<T> {
+ type Target = T;
+
+ fn deref(&self) -> &T {
+ &self.0
+ }
+}
+
fn main() {
// Storing `i32` value on heap
let b = Box::new(5);
@@ -11,4 +29,34 @@ fn main() {
use crate::List::{Cons, Nil};
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
+
+ // Dereferencing
+ let x = 5;
+ let y = &x;
+
+ assert_eq!(5, x);
+ assert_eq!(5, *y);
+
+ let x = 5;
+ let y = Box::new(x);
+
+ assert_eq!(5, x);
+ assert_eq!(5, *y);
+
+ let x = 5;
+ let y = MyBox::new(x);
+
+ assert_eq!(5, x);
+ assert_eq!(5, *y); // `*y` is equivalent to `*(y.deref())`
+
+ fn hello(name: &str) {
+ println!("Hello, {}", name);
+ }
+
+ // Deref coercion
+ let m = MyBox::new(String::from("Rust"));
+ // `&MyBox<String>` -> `&String` -> `&str`
+ hello(&m);
+ // `m`: MyBox<String>, `*m`: String, `(*m)[..]`: str, `&(*m)[..]`: &str
+ hello(&(*m)[..]);
}