I want to implement a trait for both a for reference and non-reference type. Do I have to implement the functions twice, or this is not idiomatic to do so?
Here's the demo code:
struct Bar {}
trait Foo {
fn hi(&self);
}
impl<'a> Foo for &'a Bar {
fn hi(&self) {
print!("hi")
}
}
impl Foo for Bar {
fn hi(&self) {
print!("hi")
}
}
fn main() {
let bar = Bar {};
(&bar).hi();
&bar.hi();
}
This is a good example for the Borrow
trait.
use std::borrow::Borrow;
struct Bar;
trait Foo {
fn hi(&self);
}
impl<B: Borrow<Bar>> Foo for B {
fn hi(&self) {
print!("hi")
}
}
fn main() {
let bar = Bar;
(&bar).hi();
&bar.hi();
}
No, you do not have to duplicate code. Instead, you can delegate:
impl Foo for &'_ Bar {
fn hi(&self) {
(**self).hi()
}
}
I would go one step further and implement the trait for all references to types that implement the trait:
impl<T: Foo> Foo for &'_ T {
fn hi(&self) {
(**self).hi()
}
}
See also:
&bar.hi();
This code is equivalent to &(bar.hi())
and probably not what you intended.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With