Is it possible to automatically define fields of a struct?

Viewed 2207

I'm using a macro to implement a trait as part of my library. This implementation requires the struct to have at least one additional field.

pub trait Trait {
    fn access_var(&mut self, var: bool);
}

macro_rules! impl_trait {
    (for $struct:ident) => {
        impl Trait for $struct {
            pub fn access_var(&mut self, var: bool) {
                self.var = var; // requires self to have a field 'var'
            }
        }
    }
}

I want to prevent the user from having to add those additional fields every time. Due to the fact that the Rust compiler does not allow macros in field definitions (I have no source for this, so please correct me if I'm wrong), something like this does not work.

macro_rules! variables_for_trait {
    () => {
        var: bool,
    }   
};

struct Foo {
    variables_for_trait!(); // error: expected ':' found '!'
    additional_var: i64,
}

I guess that I could create a macro which enables something like this

bar!(Foo with additional_var: i64, other_var: u64);

to look like that after resolving the macro:

pub struct Foo {
   var: bool,
   additional_var: i64,
   other_var: u64,
}

impl Trait for Foo {
   pub fn access_var(&mut self, var: bool) {
        self.var = var;
   }
}

Is there a better way to solve this, and if not, can you give me an example syntax for bar!?

P.S: What would be a good name for something like bar!?

1 Answers
Related