gpt4 book ai didi

rust - 有没有办法获取特征的类型名称?

转载 作者:行者123 更新时间:2023-11-29 08:06:15 24 4
gpt4 key购买 nike

我正在尝试使用 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"

最佳答案

这实际上是explained in the docs很好:

Generally, Self : Sized is used to indicate that the trait should not be used as a trait object. If the trait comes from your own crate, consider removing this restriction.

如果你想使用特征对象,我猜你想要,因为否则获取特征名称没有意义,你必须从特征定义中删除 Sized 约束.

话虽这么说,你确定你需要内在函数吗?很可能有更好的方法,它也可以让您在将来使用稳定的 Rust。

关于rust - 有没有办法获取特征的类型名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44305216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com