Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust method that returns token name as a string

Tags:

macros

rust

The stringify macro returns the string of a token passed to it:

struct A;

fn main() {
    let my_identifier = A {};
    assert!(stringify!(my_identifier) == "my_identifier");
}

[playground]

Is there a way to for a method to return the string of the token on which it is called?

Something like:

struct A;

impl A {
    fn token_to_string(&self) -> &str{
        /* ... */
    }
}

fn main() {
    let my_identifier = A {};
    assert!(my_identifier.token_to_string() == "my_identifier");
}

[playground]

Googling for this has not been fruitful. I'm not sure if it's possible, but I thought it reasonable to ask here before diving into the implementation of stringify which would be my next step in investigating this.

like image 863
Liam Avatar asked Nov 22 '25 22:11

Liam


1 Answers

No, this is not possible. These two constructs execute at different times in different contexts.

Macros execute during the process of compilation, and thus have access to all of the information about the original source files. This means they are able to process individual source tokens and perform operations based on them.

Methods execute when your program itself runs, and only have access to their arguments, and global variables. They have no data about the original sourcecode of the application, because that information is not stored in the compiled binary.

like image 68
loganfsmyth Avatar answered Nov 26 '25 15:11

loganfsmyth