Concatenating type name with suffix in macros

With a macro, I can create a type based on a typename passed into the macro.

But how can I generate a new type name by combining the passed in name with a sufffix?

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

#![allow(unused)]

macro_rules! DefineMyType {
    ($t:tt) => {

        struct $t;

        impl $t {
            fn print() {
                println!("hello");
            }
        }

    };
}

DefineMyType!(TestType);

fn main() {

    TestType::print();

}

But I want the type generated to be

struct $t_Suffix;

paste! should work: https://docs.rs/paste/1.0.0/paste/

1 Like

To illustrate:

use ::paste::paste;

macro_rules! DefineMyType {(
    $TyName:ident
) => (paste! {
    struct [< $TyName Suffix >];

    impl [< $TyName Suffix >] {
        fn print ()
        {
            println!("hello");
        }
    }
})}

DefineMyType!(TestType);

fn main ()
{
    TestTypeSuffix::print();
}

An alternative is to have the macro produce a module instead of using an ad-hoc namespace:

#![allow(unused)]

macro_rules! DefineMyModule {
    ($t:tt) => {
        mod $t {
            pub struct Suffix;

            impl Suffix {
                pub fn print() {
                    println!("hello");
                }
            }
        }
    };
}

DefineMyModule!(my_test);

fn main() {

    my_test::Suffix::print();

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