是否可以使用其中一种方法获取结构的名称?

ken*_*ait 2 reflection types rust

例如:

struct ABC;

impl ABC {
    fn some_method(&self) -> &str {
        // return the name of its struct -> "ABC"
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在编写Python扩展,我需要一种方法来返回其repr方法的当前结构名称.在Python中,我可以使用它self.__class__.__name__.Rust中有类似的东西吗?

lje*_*drz 5

这可能是夜间和core_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
}
Run Code Online (Sandbox Code Playgroud)