I'm trying to abstract over &T
and T
, so that I can write generic functions to deal with &T
and T
at the same time. And, I want to avoid unnecessary copy and runtime overhead, so Borrow<T>
and Cow<T>
are not good enough. I have problem when dealing with match
, I don't know how to abstract it, so I came up with a suboptimal solution, that is, add a recovery method to the trait which returns a Cow<T>
so I can do match
manually. And I think this solution will not sacrifice performance because compiler is able to optimize out the conversion. But still, it's not the optimal solution. So do you have any idea that will help?
use std::borrow::Cow;
trait CopyOnNeed<T> {
fn borrow(&self) -> &T;
fn own(self) -> T;
fn to_cow(self) -> Cow<T>;
}
impl<'a, T:Clone> CopyOnNeed<T> for &'a T {
fn borrow(&self) -> &T {
self
}
fn own(self) -> T {
self.clone()
}
fn to_cow(self) -> Cow<T> {
Cow::Borrowed(self)
}
}
impl<T> CopyOnNeed<T> for T {
fn borrow(&self) -> &T {
self
}
fn own(self) -> T {
self
}
fn to_cow(self) -> Cow<T> {
Cow::Owned(self)
}
}