Convert string ident to variable one

I want to make a new Ident from string. But it gives error like this:

self.to_string()" is not a valid Ident

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a17cdca42f33c46e5b7e46a504273ede

use proc_macro2::{Ident, Span};
use quote::{quote};
fn main() {
    let param1 = String::from("{}_{}");
    let param2 = String::from("self.to_string()");
    let param_ident = Ident::new(param2.as_str(), Span::call_site());
    println!("{}", quote! { format!(#param1, prefix, #param2) });
}

The Ident struct encapsulates valid identifiers in rust. So "self" would be valid, and "to_string" would be valid. However "self.to_string" is not a valid identifier (i.e. you can't use it as a variable name or keyword). Similarly adding the parenthesis also makes it not a valid identifier.
See: proc_macro2::Ident - Rust

Did you mean to write:

    let param2 = String::from("self.to_string()");
-   let param_ident = Ident::new(param2.as_str(), Span::call_site());
+   let param_ident = param2.parse::<::proc_macro2::TokenStream>().unwrap();

It looks to me that you wanted to "unstringify" "self.method()" to inject it as code to quote!; and they way to do that is by .parse()ing it as such.

2 Likes

yeah, this is want i wanted. thxs

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.