Reflection 是否可以使用结构的某个方法获取结构的名称?
例如:Reflection 是否可以使用结构的某个方法获取结构的名称?,reflection,types,rust,Reflection,Types,Rust,例如: struct ABC; impl ABC { fn some_method(&self) -> &str { // return the name of its struct -> "ABC" } } 我正在编写Python扩展,我需要一种方法来为其repr方法返回当前结构的名称。在Python中,我可以使用self.\uuuuuu class.\uuuuu.\uuuu name.\uuuuuuu来实现这一点。Rust中有类
struct ABC;
impl ABC {
fn some_method(&self) -> &str {
// return the name of its struct -> "ABC"
}
}
我正在编写Python扩展,我需要一种方法来为其
repr
方法返回当前结构的名称。在Python中,我可以使用self.\uuuuuu class.\uuuuu.\uuuu name.\uuuuuuu
来实现这一点。Rust中有类似的东西吗?夜间和core\u intrinsics
功能可能会:
#![feature(core_intrinsics)]
use std::intrinsics::type_name;
struct ABC;
impl ABC {
fn some_method(&self) -> &'static str {
unsafe { type_name::<Self>() }
}
}
fn main() {
println!("{}", ABC.some_method()); // ABC
}
#![特征(核心要素)]
使用std::intrinsics::type_name;
结构ABC;
实施ABC{
fn一些方法(&self)->&str{
不安全{type_name::()}
}
}
fn main(){
println!(“{}”,ABC.some_method());//ABC
}
请具体查看。@Shepmaster我正在编写Python扩展,我需要一种方法来返回当前结构的名称,我想您已经熟悉它的\uuuu repr\uuu
方法了吧?我本以为他们有工具帮你做这件事。是的,这就是我在用的。这种“内省”在《铁锈》中不受鼓励吗?我不会说是气馁,只是不常见。实际上,Debug
宏也做同样的事情,并且使用稳定的Rust。这就是为什么我希望PyO3有一个解决方案。