I have a function currently accepts a Box<dyn X>
by move.
trait X {}
impl X for i32 {}
fn func(input: Box<dyn X>) { .. }
// called as:
func(Box::new(0));
For ergonomic reasons, I'd also like to allow it to accept concrete types that implement X
by move, and have the function Box the input itself. Essentially it should allow any owned value.
// func calls Box::new internally.
func(0);
I've gotten what I want by applying a blanket impl on Box, which then allows using Into for the input:
impl<T: 'static> From<T> for Box<dyn X> where T: X {
fn from(v: T) -> Box<dyn X> {
return Box::new(v);
}
}
fn func<T: Into<Box<dyn X>>>(_input: T) { .. }
func(0); // works!
func(Box::new(0)); // works!
But the fact that this blanket impl doesn't exist makes me wonder if there's a better way. What's the best way to have a function accept any owned trait object or concrete type, like this?