Separation of concerns with derive attribute


I am pretty new to rust and trying to design what I feel is cleanish code. I will pick on the diesel crate for my example, but it can apply to any derivable trait.

Say I have an app with a file that holds my models, which are just structs. For example:
pub struct Foobar { pub id: String }. I want this file to be pretty clean so I do not put anything else in it, but I want to use these models with the diesel crate, which means I need to implement the Queryable trait for example.

Most examples will use #[derive(Queryable)] on their struct in the same file. But I want to have another file just for my database code, lets call it In i want to implement Queryable for my Foobar struct. I know I can use the impl block to accomplish this, but lets face it I want the benefits of #[derive].

Is there a way to use #[derive(Queryable)] on my Foobar struct in the file or use the benefits of derive somehow? Are there better designs that may help? I could see wrapping Foobar in a new type (thereby creating “database models”), but I am trying to see if there is a simple solution.



There’s not really a way to do this. Since derive is like a macro, it operates at the source code level and it actually needs the original source code for the struct definition in order to be able to generate the implementation.



Thank you @jethrogb! That saves me a bunch of time crawling round the internet trying to find something.