-
-
Save rust-play/495a3ff016dd14191a112e24e121a3e8 to your computer and use it in GitHub Desktop.
Code shared from the 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 Wrapper(String); | |
| impl std::ops::Deref for Wrapper { | |
| type Target = String; | |
| fn deref(&self) -> &String { | |
| &self.0 | |
| } | |
| } | |
| impl Wrapper { | |
| // This inherent method takes precedence over deref targets | |
| fn len(&self) -> usize { | |
| 999 | |
| } | |
| } | |
| fn main() { | |
| let w = Wrapper("hello".to_string()); | |
| // 1. Calls the inherent method on `Wrapper` | |
| println!("Inherent method: {}", w.len()); // Outputs: 999 | |
| // 2. Explicitly dereferencing to call the String's method | |
| println!("Explicit dereference: {}", (*w).len()); // Outputs: 5 | |
| // 3. Alternative: Using full path syntax to call String's method | |
| println!("String trait method: {}", String::len(&w)); // Outputs: 5 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment