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.
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.
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