This seems kind of a simple idea, but i can't get my head around it.
I need to define a trait, that requires that some generic function accepts slice of a defined type.
trait SomeTrait {
type Base;
fn some_fun<T>(&self, val: T)
}
What i would like to achieve is that when i implement the trait on String type it would essentially become:
impl SomeTrait for MyStruct {
type Base = String;
fn some_fun<T: &str>(&self, val: &str)
}
If this trait was implemented for Base = Vec, then T should be &[u8], etc. What i need is that in specific structs implementation i can use passed in variable with that type. I.e. if struct is String, then it should be able to get &str out of T and use that.
The closest way to achieve what i have described that i found was to define reference lifetime at whole trait generics level, but it constraints lifetime for whole struct when it should not, because when we call some_fun the lifetime for input &str should be only dependent on calling context and be independent from MyStruct lifetime.
Both are great answers and they are applicable to my use-case. I set ToOwned as solution, because in my use-case it generalizes a bit better, though i could require Clone and achieve similar results with Deref approach.
Borrow is even nicer than ToOwned, because of the ?Sized bound on Borrowed. I just generally steer away from that trait given the unfortunate overlap of Borrow::borrow with RefCell::borrow.