For example:
struct ABC;
impl ABC {
fn some_method(&self) -> &str {
// return the name of its struct -> "ABC"
}
}
I'm writing Python extensions and I need a way to return the current struct's name for its repr method. In Python, I can get this using self.__class__.__name__. Is there anything similar in Rust?
It's possible with nightly and the core_intrinsics feature:
#![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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With