From 464864e09f465be5e3b11e96ff071038c19e623d Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Sun, 20 Sep 2020 16:35:13 +0800 Subject: Deref smart pointers --- smart_pointer/src/main.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) 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); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +use std::ops::Deref; + +impl Deref for MyBox { + 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` -> `&str` + hello(&m); + // `m`: MyBox, `*m`: String, `(*m)[..]`: str, `&(*m)[..]`: &str + hello(&(*m)[..]); } -- cgit v1.2.3