简体   繁体   中英

Macro to generate multiple struct and trait implementations from parameters

I'm trying to create a macro using macro_rules! that would generate a series of struct s along with implementations for a given trait.

A sample of what I've tried:

#[macro_export]
macro_rules! a_tree {
    ($name: literal, $fruit: literal) => {
        pub struct $name;
        impl FruitTree for $name {
            fn expected_fruit() -> f64 {
                println!("the {} tree should produce {} fruit", $name, $fruit);
                20 * $fruit
            }
        }
    };
}

pub trait FruitTree {
    fn expected_fruit() -> f64;
}

a_tree![Apple, 1];
a_tree![Cherry, 20];
a_tree![Plum, 10];
a_tree![Orange, 1.2];

Rust Playground link

I'm not sure this can be done. I don't necessarily need the println! reference to $name , if that's a type instead of a literal . But I didn't get it to work like that either.

What I would want as an output for each struct would be along these lines:

pub struct Apple;

impl FruitTree for Apple {
     fn expected_fruit() -> f64 {
         println!("the {} tree should produce fruit with a ratio of {}", "Apple", 1);
         20 * 1
     }
}

Alternatively, I could declare all the structs beforehand and have the macro generate only the trait implementations, but I'd only do this as a last resort.

Thank you!

I've figured it out.

The Rust playground

A few changes were required:

  • used ident instead of ty or literal for $name
  • added [derive(Debug)] to the generated struct to allow printing
  • fixed some f64 conversions
  • added usage example in main()

Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM