Is there a way to convert given identifier to a string in a macro?

I want to use the name of the identifier as a value basically.

macro_rules! prntln{
    ($i:ident)=>{
        println!("$i");//get $i as a value 
//rather than getting the value of $i
    }
}

fn foo(){
  let ident = "test"
  prntln!(ident); // I want the output to be "ident" instead of "test"
}
1 Like

What you're looking for is the stringify!() macro. It just pumps out the string representation of whatever token is passed in.

macro_rules! foo {
    ($i: ident) => {
        println!(stringify!($i));
    }
}
foo!(bar); // Prints `bar`.
2 Likes

that is really cool. thanks

when i try to check the source of the stringify it says compiler builtin. Just out of curiosity how could one write this by oneself? I mean does rust expose any utility to use for this purpose for instance something like proc macros?

Not in regular macros; you can't do token manipulation on a sub-token level. The only way to do that would be with a proc-macro, but since this is rather universal, it's implemented directly in the compiler.

1 Like

Thanks again. stringify just saved me writing a lot of boilerplate for checking a number of optional arguments

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.