Have a look at this short program:
use std::ops::Deref;
fn main() {
let a = ThingOne { content: ThingTwo {} };
a.do_something();
}
struct ThingOne {
content: ThingTwo
}
impl Deref for ThingOne {
type Target = ThingTwo;
fn deref(&self) -> &Self::Target {
&self.content
}
}
struct ThingTwo;
impl ThingTwo {
pub fn do_something(&self) -> () {
println!("ThingTwo did something");
}
}
The result is:
ThingTwo did something
Now, what if ThingOne
comes from some external library, and one day, the author decides to extend this type as follows:
impl ThingOne {
pub fn do_something(&self) -> () {
println!("ThingOne did something");
}
}
It's a non-breaking change, so the version number could see a minor semver bump. However, now the result of my code's execution is:
ThingOne did something
Is it safe to rely on implicit dereferencing? Are there any best practices around that?