I have a struct, and I would like to automatically generate another struct, where all the fields are Option
s instead of their type from the first struct. I need this to message an update of a database entry, where all unchanged fields are None
and all fields to be updated should be Some(T)
.
Can I do this in Rust? I would like the definition of the update struct to automatically adapt to changes in the real struct.
You can do this with a macro. There are some examples of macros that loop over all fields of a struct, notably serde_derive.
Something like this?
opt_struct! {
#[derive(Default, Debug)]
struct Foo[T] {
foo: T,
} => OptionFoo
}
-
For more powerful and with nicer ergonomics metaprogramming, you can use procedural macros.
5 Likes
Thank you everyone! I will have to dig into this properly.. especially procedural macros. This is a great video by Jon Gjengset, for anyone interested.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.