Scope of macros

krizma
1 min readApr 4, 2021

I’m using a macro to build structs that are suitable for diesel and prevent duplication of entity struct (containing the id, i.e. the one-to-one map to the table structure) and normal struct (without the id, i.e. representing a real-world object). Why it’s better to have separate type for the real-world object is described here:

https://www.yesodweb.com/book/persistent#persistent_solving_the_boundary_issue

So the original idea of the macro came from here:

My approach of doing things while learning the language is that I always start implementing things in the smallest scope (i.e. within one module), then if it turns out to be useful I refactor it into another module, and if it’s so general, then I may refactor it into another crate.

So the problem with my macro started when I tried to refactor it to another module in another file. Unfortunately it’s not clearly written in the Rustbook, how it should be done. But it’s described in the language reference:

My preferred solution now is to use path-based scope, so that I use #[macro_export] when defining the macro, and use invoke it by: crate::build_model! (…)

I hope this way it will be easier to refactor when I want to move the macro to a separate crate.

--

--