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:
#![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: paste - Rust
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();
}
2 Likes
system
Closed
5
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.