I'm trying to use std::intrinsics::type_name to get the type name of a trait but can't compile it:
#![feature(core_intrinsics)]
use std::intrinsics::type_name;
trait TestTrait: Sized {
fn test(&self);
}
struct MyStruct {}
struct GetType {}
impl GetType {
fn test_type<T: ?Sized>() {
let test = unsafe { type_name::<T>() };
println!("{:?}", test);
}
}
fn main() {
GetType::test_type::<i32>();
GetType::test_type::<MyStruct>();
GetType::test_type::<TestTrait>();
}
Here is the error I get from the compiler
error[E0038]: the trait `TestTrait` cannot be made into an object
--> src/main.rs:23:30
|
23 | GetType::test_type::<TestTrait>();
| ^^^^^^^^^ the trait `TestTrait` cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`
Here is the output of that test when I comment the line GetType::test_type::<TestTrait>();
"i32"
"MyStruct"
Is there a way to solve this or to get the type name of a trait?
Working solution thanks to @evotopid
#![feature(core_intrinsics)]
use std::intrinsics::type_name;
trait TestTrait { // <--- remove `: Sized` constraint from here
fn test(&self);
}
struct MyStruct {}
struct GetType {}
impl GetType {
fn test_type<T: ?Sized>() { // <--- trick is in that bound
let test = unsafe { type_name::<T>() };
println!("{:?}", test);
}
}
fn main() {
GetType::test_type::<i32>();
GetType::test_type::<MyStruct>();
GetType::test_type::<TestTrait>();
}
Leading to the following output
"i32"
"MyStruct"
"TestTrait"