I have a method that I need to call with a trait parameter (let's call it Listener
). The reason is that sometimes I have previously stored this trait parameter into a parent structure so it is inside a Box
, and sometimes not.
So I have the two methods :
fref<T>(t: &T) where T: Listener
fbox(t: &Box<dyn Listener>)
and I would like both of them to call f(t: ??)
. For now I duplicated the code in fref
and fbox
which works but is not good. So I am looking for a signature of f
that would make it callable from fref
and fbox
to factorize my code. I was hoping one of the traits implemented by Box
would be equivalent to a &
(or at least find a common ground somewhere).
I tried the following:
- Writing
f<T>(t: &T) where T: Listener
but then I can't call fromfbox
(Listener
is not implemented byBox<dyn Listener>
). Then changing the call from within
fbox
tof(&*t)
to unbox myBox<Listener>
but sincet
is notSize
d I can't.Writing
f<T>(t: &T) where T: std::borrow::Borrow<Listener>
but then I can't call fromfref
(Borrow
is not implemented byListener
)- Same with
AsRef<Listener>
- Last attempt with
Deref
playground:
trait Listener {}
struct Mouse {}
impl Listener for Mouse {}
fn fbox(t: &Box<Listener>) {
f(t);
}
fn fref<T>(t: &T)
where
T: Listener,
{
f(t);
}
fn f<T>(_t: &T)
where
T: std::ops::Deref<Target = Listener>,
{
}
fn create_listener() -> impl Listener {
Mouse {}
}
fn main() {
let mouse = create_listener();
let box_mouse: Box<Listener> = Box::new(Mouse {});
fref(&mouse);
fbox(&box_mouse);
}