Last active
March 18, 2020 13:56
-
-
Save NebulaFox/583a88f6d373997e8e7fdfbfa48461a5 to your computer and use it in GitHub Desktop.
Deref example
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
| use std::ops::Deref; | |
| use rand; // 0.7.3 | |
| use rand::Rng; | |
| #[derive(Debug, PartialEq)] | |
| struct Wrap<T> { | |
| inside: T | |
| } | |
| impl<T> Wrap<T> { | |
| fn new(inside: T) -> Wrap<T> { | |
| Wrap { | |
| inside | |
| } | |
| } | |
| } | |
| impl<T> Deref for Wrap<T> { | |
| type Target = T; | |
| fn deref(&self) -> &T { | |
| &self.inside | |
| } | |
| } | |
| fn make_a_string_with(string: &str) -> String { | |
| let mut s = String::new(); | |
| s.push_str(string); | |
| let mut rng = rand::thread_rng(); | |
| let r = rng.gen_range(0, 100); | |
| for _ in 0..r { | |
| s.push_str("!"); | |
| } | |
| s | |
| } | |
| fn main() { | |
| let string = String::new("Hello World"); | |
| let wrap = Wrap::new(string); | |
| let result = make_a_string_with(&wrap); // deref coercions | |
| println!("len: {}, string: {}", result.len(), result); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment