im writing this answer for people who want to implement their custom type that has an inner type and then call the inner's type methods without writing wrapper functions.
this is a handy situation for struct composition/aggregation, where you have a wrapper over a type and dont want to write every method like this:
pub fn width(&self) -> i32 {
self.inner.width()
}
pub fn height(&self) -> i32 {
self.inner.height()
}
/// and so on ...
this is actually ugly and annoying. imagine if you have 100 methods to wrap ...
here's the small example:
use std::ops::Deref;
pub struct Inner {}
impl Inner {
pub fn just_a_method(&self) -> i32 {
32
}
}
struct DerefExample<T> {
inner: T,
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
fn main() {
let x = DerefExample {
inner: Inner {}
};
let result = (*x).just_a_method();
println!("(*x).just_a_method() == {}", result);
let result = x.just_a_method();
println!("x.just_a_method() == {}", result);
}
note that both methods of calling the just_a_method
work the same. the second time the compiler automatically dereferences the x
to get the inner type.
program output:
(*x).just_a_method() == 32
x.just_a_method() == 32
(*a).contains("white")
automatically? can i implement deref on my custom type? and then call its inner type methods without writing*object
everytime? – Jollity