I'm relatively new to Rust and I'm exercising with macros.
The goal is to archive some sort if React-ish syntax within Rust lang.
I’m aware of the drastic DSL approach like jsx!(<div />)
, which is a good solution but of another topic. I’m seeking something in the middle, more like Flutter or SwiftUI syntax, which leverages the native language feature as much as possible, but still presents a visually hierarchical code structure.
Here I'm exploring the idea of constructing a View
struct using a children!
macro.
My main intension here is to enable View.children
field to hold an arbitrary arity tuple. Since variadic generic tuple is not available in Rust yet, macro seems to be the only option.
See the code and comment:
struct View<T> {
// children field holds arbitrary nullable data
// but what i really want is Variadic Tuple, sadly not available in rust
children: Option<T>,
}
// `children!` macro is a shorthand for Some(VariadicTuple)
// so to avoid the ugly `Some((...))` double parens syntax.
macro_rules! children {
($($x:expr),+ $(,)?) => (
Some(($($x),*))
);
}
fn main() {
let _view = View {
children: children!(
42,
"Im A String",
View {
children: Some(("foo", "bar")),
},
),
};
}
So far so good. Now there's this final part I really want to further optimize:
View {
children: children!(...) }
Is it possible to call a macro right inside the struct body, (instead of at the value
position after a field:
syntax) so to eliminate the need to write children:
field redundantly?