Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the name of a struct using one of its methods? [duplicate]

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?

like image 208
kentwait Avatar asked Oct 28 '25 17:10

kentwait


1 Answers

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
}
like image 171
ljedrz Avatar answered Oct 30 '25 07:10

ljedrz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!