2017-06-01 109 views
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" 

回答

3

这实际上是explained in the docs相当不错:

一般来说,Self : Sized使用以表明该性状不应该被用作特征对象。如果特质来自你自己的箱子,考虑取消这个限制。

如果你想使用特质的对象,我想你想要的,因为否则就没有意义获得性状的名字,你必须从你的特征定义删除Sized约束。

这就是说,你确定你需要内在?最有可能的是有一个更好的方法,这也可以让你在将来使用稳定的Rust。

+0

感谢您的回答@evotopid。如果我删除'Sized'约束,我仍然无法获得'GetType :: test_type :: ();'来编译(请参阅我的更新后的编译错误消息)。 解决此问题的唯一方法是调用'GetType :: test_type :: >();'这非常麻烦(我仍然可以解析字符串以获得我想要的内容,但调用有点奇怪) 我想获取特征名称作为字符串,然后在地图中使用,而不是作为特征对象。我阅读了关于内在函数的警告,但找不到另一种方式来获得这个 – Boris

+0

这似乎是工作? https://play.rust-lang.org/?gist=8b8220dc22bfb9ffc070ac9c6748d38e&version=nightly&backtrace=0 – evotopid

+0

事实上,我需要在'test_type()'函数中添加''约束。非常好,谢谢 (编辑我原来的问题给读者) – Boris

相关问题