-
-
Save greister/c0aee3e05833abde231119599afbb15b to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Book { | |
name: String | |
} | |
impl Book { | |
fn show_book_name(&self) { | |
println!("Name is : {}", self.name); | |
} | |
} | |
use std::ops::{Deref, DerefMut}; | |
struct MyBook { | |
p: Book, | |
author: String, | |
} | |
impl MyBook { | |
fn new() -> MyBook { | |
MyBook { | |
p: Book{ name: "知乎大全".to_string()}, | |
author: "我是谁".to_string() | |
} | |
} | |
} | |
impl Deref for MyBook { | |
type Target = Book; | |
fn deref<'a>(&'a self) -> &'a Book { | |
&self.p | |
} | |
} | |
fn main() { | |
let mut mybook = MyBook::new(); | |
mybook.show_book_name(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good . example for using Deref.