Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active June 17, 2026 11:33
Show Gist options
  • Select an option

  • Save RandyMcMillan/1e53a439746a61c4627d8e034b724cd1 to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/1e53a439746a61c4627d8e034b724cd1 to your computer and use it in GitHub Desktop.
deref_coercion.rs
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
}
@RandyMcMillan

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment