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();
}
You can use
Cow
:The one advantage over
Borrow
is that you know if the data was passed by value or reference, if that matters to you.This is a good example for the
Borrow
trait.No, you do not have to duplicate code. Instead, you can delegate:
I would go one step further and implement the trait for all references to types that implement the trait:
See also:
This code is equivalent to
&(bar.hi())
and probably not what you intended.See also: