2

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
kentwait
  • 1,969
  • 2
  • 21
  • 42
  • See specifically [this answer](https://stackoverflow.com/a/29168659/155423). – Shepmaster Feb 01 '19 at 15:28
  • 1
    @Shepmaster I'm writing Python extenstions and I needed a way to return the current struct's name for its `__repr__` method – kentwait Feb 01 '19 at 15:51
  • You are already familiar with [PyO3](https://github.com/PyO3/pyo3), I assume? I would have thought they had tools to do this for you. – Shepmaster Feb 01 '19 at 15:52
  • Yes, that's what I'm using. Is this kind of "introspection" not encouraged in Rust? – kentwait Feb 01 '19 at 16:01
  • 1
    I wouldn't say discouraged, just uncommon. The `Debug` macro does the same thing, really, and uses stable Rust. That's why I'd expect the PyO3 to have a solution. – Shepmaster Feb 01 '19 at 16:48

1 Answers1

8

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
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ljedrz
  • 20,316
  • 4
  • 69
  • 97