'What code will actually be generated when a generic struct implements `Deref`?
I can't really understand the dereference here. The type of foo is TattleTell<&str>. The method len() is from foo.value, i.e. foo.value.len(). So why deref of TattleTell is invoked?
use std::ops::Deref;
struct TattleTell<T> {
value: T,
}
impl<T> Deref for TattleTell<T> {
type Target = T;
fn deref(&self) -> &T {
println!("{} was used!", std::any::type_name::<T>());
&self.value
}
}
fn main() {
let foo = TattleTell {
value: "secret message",
};
// dereference occurs here immediately
// after foo is auto-referenced for the
// function `len`
println!("{}", foo.len());
}
Solution 1:[1]
I won't fully describe Rust's auto-dereferencing rules because they are covered in other answers. For example, here.
In your case, you are trying to call a method, len, on a TattleTell<&'static str>. This type doesn't directly have that method so, using the rules in that other answer, Rust goes looking for it, using the following steps:
- Check if the method exists on
&TattleTell<&'static str>. It doesn't. - Check if the method exists on
*&TattleTell<&'static str>. Due to yourDerefimplementation, this is a&'static str, so the method exists.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Hall |
