diff options
author | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-20 16:35:13 +0800 |
---|---|---|
committer | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-20 16:35:13 +0800 |
commit | 464864e09f465be5e3b11e96ff071038c19e623d (patch) | |
tree | 8327ab714b5694fc84cda0c44c5d15c5e0fe939b /smart_pointer/src | |
parent | f91da817be5688f052bce317b1f70ad7176fd13b (diff) |
Deref smart pointers
Diffstat (limited to 'smart_pointer/src')
-rw-r--r-- | smart_pointer/src/main.rs | 48 |
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)[..]); } |