I wish to have an implementation for a struct with a generic that works when the generic is of a certain trait and ALSO when it is a reference to a value of the trait without duplicated code.
Here is a short example of the functionality I wish to have:
struct Foo<T>(T);
impl<T> Foo<T>
where
T: Bar,
{
fn foo_bar(&self) {
self.0.trait_method();
}
}
trait Bar {
fn trait_method(&self) {
println!("trait method called");
}
}
struct Baz;
impl Bar for Baz {}
fn main() {
let baz_move = Baz;
let foo1 = Foo(baz_move);
// works as expected, outputting "trait method called":
foo1.foo_bar();
let baz_ref = Baz;
let foo2 = Foo(&baz_ref);
// doesn't compile:
// foo2.foo_bar();
}
I understand why it doesn't compile but is there a nice way to make it work without code repetition/duplication? And also preferably a solution in the case where you do not have "ownership" of the said trait (unlike the example where the trait is in the same module, of course).