2
我试图用std::intrinsics::type_name
获得性状的类型名称,但不能编译:有没有办法获得特征的类型名称?
#![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>();
}
以下是错误我从编译器获得
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`
这里是该测试的输出,当我评论线GetType::test_type::<TestTrait>();
"i32"
"MyStruct"
有没有办法解决这个或获得性状的类型名称的方法吗?
工作液感谢@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>();
}
通往下面的输出
"i32"
"MyStruct"
"TestTrait"
感谢您的回答@evotopid。如果我删除'Sized'约束,我仍然无法获得'GetType :: test_type ::();'来编译(请参阅我的更新后的编译错误消息)。 解决此问题的唯一方法是调用'GetType :: test_type :: >();'这非常麻烦(我仍然可以解析字符串以获得我想要的内容,但调用有点奇怪) 我想获取特征名称作为字符串,然后在地图中使用,而不是作为特征对象。我阅读了关于内在函数的警告,但找不到另一种方式来获得这个 –
Boris
这似乎是工作? https://play.rust-lang.org/?gist=8b8220dc22bfb9ffc070ac9c6748d38e&version=nightly&backtrace=0 – evotopid
事实上,我需要在'test_type()'函数中添加''约束。非常好,谢谢 (编辑我原来的问题给读者) –
Boris