Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created June 17, 2026 11:31
Show Gist options
  • Select an option

  • Save rust-play/495a3ff016dd14191a112e24e121a3e8 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/495a3ff016dd14191a112e24e121a3e8 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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