2

Is there any way to create a macro in rust that returns a new struct with the fields that I want. I have been working on this for weeks and cannot find a suitable solution. Seeing the problem below, is this even possible? And if so, how would I go about starting to implement this?

struct Person {
    id: u32,
    first_name: String,
    middle_name: Option<String>,
    last_name: String,
    age: u8,
}

// I want to be able to have a function-like macro 
// that takes the new name, old struct, and fields I want as input
// and returns a new struct based on that

sub_struct!("PersonNames", &Person, vec!["first_name", "middle_name", "last_name"])

// the above code yields the following
struct PersonNames {
    first_name: String,
    middle_name: Option<String>,
    last_name: String,
}

another solution I can think of trying that I haven't yet is using derive-like macros.

#[sub_struct(&Person, vec!["first_name", "middle_name", "last_name"])]
struct PersonName {}
Big G
  • 211
  • 1
  • 9
  • 1
    The first solution can't work because a macro can only see what it is passed, e.g. its arguments and in the case of an attribute macro the item to which it is attached. The second one should be possible. – Jmb Mar 31 '22 at 15:01
  • Is there a way to get the type of an specific attribute for a specific struct in rust? – Big G Mar 31 '22 at 15:03
  • Couldn't you just put a `names: PersonNames` field inside `Person`, instead of separate fields? I know your actual situation is probably different, so it might help if you describe why you need this in the first place. – Thomas Mar 31 '22 at 15:04
  • 1
    @Thomas It is mainly because I am lazy haha. I have 5 structs of about 20-30 fields each and need to create new structs with only parts of those fields for data parsing. (I cannot change how the data parsing is done) The only thing is that those fields are not easily categorized. Over time the different fields that I need to use will change, and possibly even the types as well. I want to only need to change one or two places in the code and not have to go through every line each time just to change a simple type or switch in/out a field for another. – Big G Mar 31 '22 at 15:12
  • If you're using serde, it lets you mark fields as optional. Not sure if that's a possibility for you. – Thomas Mar 31 '22 at 15:15
  • 1
    While the use case kind of eludes me (that is my problem, not yours), I think you could improve on the naming. What you want is a subset of the fields of a structure formed into a new structure, right? The macro-name could hence be `sub_struct` or `struct_view`, for example. Anyway - the last time I considered using Rust macros, I used emacs lisp and code generation instead. – BitTickler Mar 31 '22 at 15:33

0 Answers0