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];
I'm not sure this can be done. I don't necessarily need the println!
reference to $name
, if that's atype
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:
ident
instead of ty
or literal
for $name
[derive(Debug)]
to the generated struct to allow printingf64
conversionsmain()
Thank you!