0

I have three structs:

struct OneStruct {}
impl OneStruct {
    pub fn OneTest() {
        println!("TEST-01");
    }
}

struct TwoStruct {}
impl TwoStruct {
    pub fn TwoTest() {
        println!("TEST-02");
    }
}

struct ThreeStruct {}
impl ThreeStruct {
    pub fn ThreeTest() {
        println!("TEST-03");
    }
}

I want to write a macro that takes the struct ident and invoke its *Test method, like this:

test!(OneStruct); // "TEST-01"
test!(TwoStruct); // "TEST-02"
test!(ThreeStruct); // "TEST-03"

What I tried:

macro_rules! test(
    ($name:ident) => ({
        let name_string = &stringify!($name);
        let name_wo_struct = &name_string[0..name_string.len()-6];
        let test_method = &format!("{}{}", name_wo_struct, "Test");
        let name_ident = syn::Ident::new(name_string, syn::export::Span::call_site());
        let test_method_ident = syn::Ident::new(test_method, syn::export::Span::call_site());


        // quote!(#name_ident::#test_method_ident();)
    });
);

What's the right way to create new identifier in a Rust macro?

Playground

0x00A5
  • 1,462
  • 1
  • 16
  • 20
  • *invoke its "test" method* — your structs have no such method. – Shepmaster Feb 20 '20 at 01:01
  • You don't use `syn` or `quote` in declarative (`macro_rules!`) macros. – Shepmaster Feb 20 '20 at 01:02
  • 1
    It looks like your question might be answered by the answers of [Can a Rust macro create new identifiers?](https://stackoverflow.com/q/27415011/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Feb 20 '20 at 01:55
  • 1
    Please go ahead mark this as an already answered question. Thanks. – 0x00A5 Feb 20 '20 at 03:17

0 Answers0