I often encounter this scene,really troublesome
I defined a full struct such as
struct A {
name: String,
id: u8,
}
when I provide an external interface, I need this,which is identical except without a field name
struct A {
id: u8,
}
When i don`t want to define two struct ,I need change to this one
struct A {
name: Option<String>,
id: u8,
}
But i don't like this way ,I think the macros may do me a favor ,but don't know,Is there a way to accomplish this;
such as
// I defined a full struct
#[derive(Debug)]
struct A {
name: String,
id: u8,
}
// then derive struct A,I got struct B
#[derive(Omit(A,"name"))]
struct B {}
// struct B equals
// struct B {id:u8}
It's doable but not quite the way you've written it. In a situation like this
#[derive(Omit(A,"name"))]
struct B {}
the macro only gets struct B {} as its input, it can't know what fields A has. Also, a derive macro cannot modify its input, it can only output additional code, so a derive macro couldn't change B's definition even if it knew what fields A had.
A macro that did this would probably look something like this
#[omit(B, name)]
struct A {
name: String,
id: u8,
}
The macro would be relatively simple and I think it'd be a good first proc macro if you haven't written any before.
Personally I would probably still make it a derive macro since it doesn't need to modify the original type definition, but I can see the argument for using an attribute macro.
If you haven't written a proc macro before I would recommend taking a look here
It walks you through getting started with the various different kinds of proc macros.