I'm trying to hold a Box, but unburden the caller from caring whether they need to pass a T: Something
or a Box<dyn Something>
or a Box<T: Something>
.
Basically in this code, I would like to make let why_not = Greeter::new(Box::new(Hello));
also compile.
Can anyone point me in a direction for this?
trait Greet {
fn greet(&self) -> &'static str;
}
impl<T: Greet + 'static> From<T> for Box<dyn Greet> {
fn from(g: T) -> Self {
Box::new(g)
}
}
struct Hello;
impl Greet for Hello {
fn greet(&self) -> &'static str {
"hello"
}
}
struct Greeter {
inner: Box<dyn Greet>,
}
impl Greeter {
// Can this function take either a `T: Greet` or a `Box<dyn Greet + 'static`?
fn new<T: Into<Box<dyn Greet>>>(greet: T) -> Self {
Self {
inner: greet.into(),
}
}
fn print(&self) {
println!("{}", self.inner.greet())
}
}
fn main() {
let greeter = Greeter::new(Hello);
let why_not = Greeter::new(Box::new(Hello));
greeter.print();
why_not.print();
}
36 | let why_not = Greeter::new(Box::new(Hello));
| ^^^^^^^^^^^^^^^
| |
| expected an implementor of trait `From<Box<Hello>>`
| help: consider borrowing here: `&Box::new(Hello)`