-
-
Save RandyMcMillan/1e53a439746a61c4627d8e034b724cd1 to your computer and use it in GitHub Desktop.
deref_coercion.rs
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 | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=495a3ff016dd14191a112e24e121a3e8