Edit: I was trying to figure out how to work with a generic type that is never mutated and be able to receive it as either borrowed or owned. To somehow implement borrowed_or_owned() below without needing to have two duplicate methods:
fn borrowed(s: &str) {
println!("{}", s);
}
fn owned(s: String) {
println!("{}", s);
}
fn borrowed_or_owned(???) {
println!("{}", s);
}
It turns out the way to do this is a little bit different depending on whether your use case is a free function, trait method, or struct impl. Visit the playground for a lengthier explanation. The solution appears to be:
fn speak<T: std::fmt::Display>(ref msg: T) {
println!("{}\nI have spoken.", msg);
}
pub trait Speak {
fn speak(self);
}
impl<T> Speak for &T
where
T: std::fmt::Display + ?Sized,
{
fn speak(self) {
println!("{}\nI have spoken.", self);
}
}
struct Speaker<T: std::borrow::Borrow<T> + std::fmt::Display> {
msg: T,
}
impl<T: std::borrow::Borrow<T> + std::fmt::Display> Speaker<T> {
fn new(msg: T) -> Self {
Speaker { msg }
}
fn speak(&self) {
println!("{}\nI have spoken.", self.msg.borrow());
}
}
While trying to figure out the above I ran into some issues with type inference on std::borrow::Borrow which are solved by @EdmundsEcho's suggestion.
Original post for posterity:
I am trying to write a trait or free function that is generic over T, &T, Box<T>, etc where T is a generic type satisfying some trait bound. I can almost do this by working with std::ops::Deref, but in the case of Deref I cannot actually take T itself as an argument (i.e. has to be &T or something else that actually dereferences to T).
I would like to achieve my goal using std::borrow::Borrow but the compiler is having trouble with generic type inference, and I am struggling to understand why. It works for concrete types T but not generic T. For example:
// Trait
pub trait Speak<T: ?Sized> {
fn speak(self);
}
impl<B, T> Speak<T> for B
where
B: std::borrow::Borrow<T>,
T: std::fmt::Display + ?Sized,
{
fn speak(self) {
println!("Says, \"{}\"", self.borrow());
}
}
// Free function, doesn't use trait
fn speak<B, T>(speaker: B)
where
B: std::borrow::Borrow<T>,
T: std::fmt::Display + ?Sized,
{
println!("Says, \"{}\"", speaker.borrow());
}
fn main() {
let speaker: &str = "Hello, world!";
Speak::<&str>::speak(speaker); // OK
speak::<_,&str>(speaker); // OK
speaker.speak(); // cannot infer type for type parameter `T`
speak(speaker); // cannot infer type for type parameter `T`
// note: cannot satisfy `&str: Borrow<_>`
}
Why can't the compiler infer that T is &str? Does it have something to do with the blanket impl<T> Borrow<T> for T? Is there a more idiomatic way to accept a generic argument by value or by reference? (Note that I need this to work even for T for which the AsRef implementation is missing.)