I am playing around with trait objects and tried to write the function below.
As expected, it does not work as intended, since generics always represent types, not traits.
Just out of curiosity: Is it possible in current Rust, to implement such a generic function as below?
use std::fmt::Debug;
fn as_dyn<T, U>(input: T) -> Box<dyn U>
where
T: U,
{
Box::new(input) as Box<dyn U>
}
#[derive(Debug)]
struct Foo;
fn main() {
let d = as_dyn::<_, Debug>(Foo);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0404]: expected trait, found type parameter `U`
--> src/main.rs:5:8
|
3 | fn as_dyn<T, U>(input: T) -> Box<dyn U>
| - found this type parameter
4 | where
5 | T: U,
| ^ not a trait
error[E0404]: expected trait, found type parameter `U`
--> src/main.rs:3:38
|
3 | fn as_dyn<T, U>(input: T) -> Box<dyn U>
| - ^ not a trait
| |
| found this type parameter
error[E0404]: expected trait, found type parameter `U`
--> src/main.rs:7:32
|
3 | fn as_dyn<T, U>(input: T) -> Box<dyn U>
| - found this type parameter
...
7 | Box::new(input) as Box<dyn U>
| ^ not a trait
For more information about this error, try `rustc --explain E0404`.
error: could not compile `playground` (bin "playground") due to 3 previous errors