{"article":{"slug":"rust-declarative-macros-organization-scoping-and-common-use-cases","title":"Rust Declarative Macros: Organization, Scoping, and Common Use-Cases","subtitle":null,"summary":"A follow-up tutorial on Rust declarative macros covering how to scope, organize, and export macro_rules! macros within a crate, plus common patterns for reducing boilerplate, with real-world and toy examples.","content_type":"tutorial","language":"en","canonical_url":"https://sigseis.dev/articles/2026/11/10","author":{"name":"Sigseis","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Sigseis","url":"https://sigseis.dev/","listing_slug":null,"listing":null},"topics":[{"name":"rust","slug":"rust","url":"https://listedarticles.com/topics/rust"},{"name":"programming","slug":"programming","url":"https://listedarticles.com/topics/programming"},{"name":"tutorials","slug":"tutorials","url":"https://listedarticles.com/topics/tutorials"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":5217,"reading_minutes":23,"published_at":"2026-11-10T16:30:02.000Z","added_at":"2026-11-15T19:54:29.470Z","updated_at":"2026-11-15T19:54:29.470Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/rust-declarative-macros-organization-scoping-and-common-use-cases","markdown_url":"https://listedarticles.com/articles/rust-declarative-macros-organization-scoping-and-common-use-cases.md","example":false,"citation":"Sigseis, Sigseis. \"Rust Declarative Macros: Organization, Scoping, and Common Use-Cases.\" 10 Nov 2026. https://sigseis.dev/articles/2026/11/10 (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://sigseis.dev/articles/2026/11/10"},"body_markdown":"# Rust Declarative Macros: Organization, Scoping, and Common Use-Cases\n\n![An Oguri Cap toy from Umamusume standing in front of a fruit market set, holding a mango with a happy expression on her face.](https://sigseis.dev/articles/2026/11/10/cover.280896d925.picture/cover.jpg)\n\nIn our [previous article](https://sigseis.dev/articles/2026/10/06), we covered what declarative macros are, and how to define and use them.\n\nIn this article, we will focus on how to integrate them into your crate. That means we’ll cover macro scoping, organization, and exporting. We’ll also take a look at some common use-cases with examples.\n\nHopefully, after reading these two articles, you’ll feel ready to start experimenting with declarative macros in your own crates!\n\n> This article is tested under the 2024 edition of Rust.\n>\n> For older code you may see some older patterns, like using a lot of `#[macro_use]` statements, but this article is going to focus on more modern practices. If something doesn’t compile for you, check your Rust version and edition.\n\n[##](#article-toc)\n\n## Table of Contents\n\n- [How To Integrate Declarative Macros Into Your Crate](#how-to-integrate-declarative-macros-into-your-crate)\n  - [Scoping Rules for Declarative Macros](#scoping-rules-for-declarative-macros)\n    - [Textual Scoping Rules](#textual-scoping-rules)\n    - [Path-Based Scoping Rules](#path-based-scoping-rules)\n  - [Exporting Declarative Macros](#exporting-declarative-macros)\n  - [A Reminder About Macro Hygiene](#a-reminder-about-macro-hygiene)\n  - [How to Organize Declarative Macros](#how-to-organize-declarative-macros)\n- [Use Cases for Declarative Macros](#use-cases-for-declarative-macros)\n  - [Implementing Traits and Functions](#implementing-traits-and-functions)\n  - [`format!`-Like Expressions](#format-like-expressions)\n  - [Used for Initializing Complex Types](#used-for-initializing-complex-types)\n  - [Reducing Boilerplate](#reducing-boilerplate)\n- [Summary](#summary)\n\n[##](#how-to-integrate-declarative-macros-into-your-crate)\n\n## How To Integrate Declarative Macros Into Your Crate\n\nBroadly speaking, I like to differentiate declarative macros based on access level.\n\n- **crate-exported**: Intended to be exported from your crate and used by your dependents\n- **crate-local**: Intended to be used privately within your crate\n\n**You should prefer to keep macros crate-local if possible.**\n\nMacros can be useful even if you don’t intend on exporting them. Actually, that’s most commonly how I make use of macros!\n\nThe main way to differentiate between the two is whether a macro is marked with the `#[macro_export]` attribute. If not, then it’s a **crate-local** macro.\n\n[###](#scoping-rules-for-declarative-macros)\n\n### Scoping Rules for Declarative Macros\n\nFor historic reasons, macros have two different ways they scope into the surrounding code.\n\n- **Textual Scoping**: The macro scope is based on *where in the file it’s defined*\n- **Path-Based Scoping**: The macro becomes an item in the module tree (acting more similarly to a standard Rust item)\n\nWhere possible, you should prefer *path-based scoping*, but textual scoping can come in handy in some cases. Additionally, you’re very likely to run into heavy usage of the original textual scoping rules. So it’s worth understanding them regardless.\n\n[####](#textual-scoping-rules)\n\n#### Textual Scoping Rules\n\n**By default, declarative macros take on a textual scope.**\n\nTextual scoped declarative macros have some counter-intuitive visibility and access rules.\n\n- The macro may be used ONLY *after* its definition within a module, function, or logical scope.\n- The macro may be used by any submodules after the macro definition, *even without importing it explicitly*.\n\nSo unlike other parts of the Rust language, **order actually matters for textual scoped declarative macros**.\n\nThe most narrow visibility is within a logical scope (for example a function). Sometimes, though admittedly rarely, this can be useful for functions that have a lot of internal repetition.\n\n```\nfn example() {\n    macro_rules! helper_macro {\n        () => {};\n    }\n    helper_macro!();\n}\n\n// You cannot access this macro outside of the function.\n```\n\nIf the macro is going to be used in multiple items within the same module, you can simply define it in the module itself. This is more visible than within a single function, but it’s still constrained to only the current module and its submodules.\n\n```\n// You cannot use it here, because it's not defined yet.\n\nmacro_rules! helper_macro {\n    () => {};\n}\n\n// Now it can be invoked and used.\nhelper_macro!();\n\n// It can be used within functions, as one might expect.\nfn within_functions() {\n    helper_macro!();\n}\n\n// Works within submodules of any depth as well,\n// which might feel counter-intuitive.\nmod even_within_submodules {\n    helper_macro!();\n}\n```\n\nSometimes it can be beneficial to use a macro from the *parent* module the containing module is defined under.\n\n**Modern Rust syntax allows for this better with path-based scoping**, which we’ll learn about in the next section.\n\nThat said, you may still run into this syntax, so we should cover it.\n\nTo hoist macros defined in a submodule into the parent’s textual scope, you can attach the `#[macro_use]` attribute on the containing module.\n\n```\n// We still cannot use `helper_macro!` here, it isn't defined yet.\n\n// After the module definition completes,\n// it's now defined in the parent's textual scope.\n#[macro_use]\nmod submodule {\n    macro_rules! helper_macro {\n        () => {};\n    }\n    helper_macro!();\n}\n\n// See? Now we can access and use it here even without an import.\n// It acts as-if we had defined textually after `submodule`.\nhelper_macro!();\n\n// Works within submodules of any depth as well,\n// since it's a part of the textual scope.\nmod sibling_submodule {\n    helper_macro!();\n}\n```\n\nBut note that `#[macro_use]` will not automatically propagate further up the module tree.\n\nIf you want your macro to continue to be defined all the way up the module tree, you’ll have to continue to attach the `#[macro_use]` attribute on all the parent modules.\n\n```\n#[macro_use] // <- Necessary if you need it...\nmod outer_file {\n    #[macro_use]\n    mod other_file {\n        macro_rules! helper_macro {\n            () => {};\n        }\n        helper_macro!();\n    }\n    helper_macro!();\n}\nhelper_macro!(); // <- ... at this location onwards.\n```\n\n> Historically, `#[macro_use]` was also used to import external macros from other crates into your textual scope.\n>\n> You should not be doing this anymore for macros imported from other crates, however.\n\n[####](#path-based-scoping-rules)\n\n#### Path-Based Scoping Rules\n\nPath-based scoping for declarative macros allows us to work with macros in a way which feels more idiomatic.\n\n- The macro works a lot like any other item, and can be invoked before the definition.\n- In order to be used, it needs to be manually imported or resolved from the module tree.\n\nThis can be accomplished with a small bit of code right after the macro definition:\n\n```\nmacro_rules! helper_macro {\n    () => {};\n}\n\n// Re-export as an item in the module tree.\npub(crate) use helper_macro;\n```\n\nWhen you do this, since the macro is now a part of the module tree, order no longer matters.\n\n```\n// Can call here, even if the macro isn't defined yet.\nhelper_macro!();\n\nmacro_rules! helper_macro {\n    () => {};\n}\npub(crate) use helper_macro;\n\n// Can obviously still call here.\nhelper_macro!();\n```\n\n> Even though you can refer to macros out of order when they use path-based scoping, you’ll probably still want to define them before they’re used within the same file. Not because it’s necessary, but because it’s readable!\n\nThe real benefit of this is that other modules can import and use the macro like they would any other item.\n\n```\nmod submodule {\n    macro_rules! helper_macro {\n        () => {};\n    }\n    pub(crate) use helper_macro;\n}\n\nmod another_submodule {\n    // You can use it like a normal item!\n    use crate::submodule::helper_macro;\n    helper_macro!();\n\n    // Or you can refer to it by a path!\n    crate::submodule::helper_macro!();\n}\n```\n\nIt’s most common to see this used with `pub(crate)`, but you can really use all item visibilities here (`pub(super)`, `pub(in some::path)`, *empty for private*). `pub` has some strange properties, however - we’ll cover that in the next section.\n\n[###](#exporting-declarative-macros)\n\n### Exporting Declarative Macros\n\nIf you want a declarative macro to be usable from outside your crate, you have to attach the `#[macro_export]` attribute to it.\n\n**Be careful when deciding to export a macro!**\n\nAfter you export a macro, users may grow to depend on it, and it may become difficult to change or maintain. This is why I usually err towards *not* exporting a macro, until I’m *sure* it’s warranted.\n\nStill, if you’re sure it’s the right thing to do, you can accomplish it like so:\n\n```\n#[macro_export]\nmacro_rules! exported_macro {\n    () => {};\n}\n\nmod submodule {\n    use crate::exported_macro;\n    exported_macro!();\n}\n```\n\nThe observable effects of this attribute are:\n\n- The root of your crate will publicly export the macro for dependents to use (`use your_crate::exported_macro`).\n- You can privately import the macro using normal path-based scoping (`use crate::exported_macro`).\n\nIt doesn’t matter whether the macro is in a submodule or not, it will *always* export at the root.\n\n```\nexported_macro!(); // <- Works because of `#[macro_export]`\nmod module {\n    use crate::exported_macro;\n\n    exported_macro!(); // <- Works because of the `use` statement\n    mod submodule {\n        #[macro_export]\n        macro_rules! exported_macro {\n            () => {};\n        }\n    }\n    exported_macro!(); // <- Works because of the `use` statement\n}\nexported_macro!(); // <- Works because of `#[macro_export]`\n```\n\nThe `#[macro_use]` attribute still has an effect privately within your crate, as one would expect for textual scoping rules. Though, I don’t recommend using it on modules containing exported macros, instead just go through the exported path.\n\n```\nexported_macro!(); // <- Works because of `#[macro_export]`\nmod module {\n    // <- Would not be usable here without a `use` statement\n\n    #[macro_use]\n    mod submodule {\n        #[macro_export]\n        macro_rules! exported_macro {\n            () => {};\n        }\n    }\n    exported_macro!(); // <- Works because of `#[macro_use]`\n}\nexported_macro!(); // <- Works because of `#[macro_export]`\n```\n\nIf you want to export a macro somewhere *other* than the crate root, there’s a way to allow for that.\n\nIt would be nice if you could just not use `#[macro_export]`, and instead `pub use exported_macro`, but as for now this doesn’t work. If you try it, you will be met with a compile error that the macro is “only public within the crate, and cannot be re-exported”.\n\nSo, you *MUST* use `#[macro_export]` on exported macros. Then, you can bind that exported macro to a specific location in the module tree with `pub use exported_macro`.\n\nThat’s annoying since it’ll publish a macro in the root (which you probably don’t intend), so the general pattern for this is:\n\n1. Hide the publicly exported macro (so folks can’t see it’s actually at the root).\n2. Create a public path binding in the module where you want the macro to be accessed from.\n\nSo, for instance:\n\n```\npub mod submodule {\n    // Since this is `#[macro_export]`,\n    // it will still wind up at the crate root.\n    //\n    // Because of that, we name this in a way that deters usage.\n    // We'll also hide it, so that it doesn't appear in docs.\n    #[doc(hidden)]\n    #[macro_export]\n    macro_rules! __exported_macro {\n        () => {};\n    }\n\n    /// The actual documentation will go here!\n    #[doc(inline)]\n    pub use __exported_macro as exported_macro;\n}\n\n// Technically this does export the following macro...\ncrate::__exported_macro!();\n\n// However, documentation will only list this version.\n// And, this version will be public for dependents to use.\ncrate::submodule::exported_macro!();\n```\n\n> In future versions of Rust, this cruft around visibility and module tree exporting may get cleaned up.\n>\n> It’s hard to make changes like this to the Rust language that won’t break existing code. So this has remained one of those weird parts of the language which - if you’re not careful - can work in odd, non-idiomatic ways.\n>\n> There’s a pretty in-depth thread about this [here](https://internals.rust-lang.org/t/pub-on-macro-rules/19358) on the Rust internals forum.\n\n[###](#a-reminder-about-macro-hygiene)\n\n### A Reminder About Macro Hygiene\n\nRecall from our prior article, when we talked about [macro hygiene](https://sigseis.dev/articles/2026/10/06#what-s-this-macro-hygiene-thing), that Rust uses what’s known as “mixed-site hygiene”.\n\nMost items - other than local variables - are resolved from where the macro is invoked (functions, types, traits, etc.). For crate-local macros, you can be a little looser with this and require that the invoking code imports some items as needed to compile. But for crate-exported macros, it’s not a good idea to force the user to do this.\n\nBecause of that, you should keep the following things in mind:\n\n- You usually want to avoid using the `crate` keyword directly, because it may not refer to *your* crate.\n- Since you’re in less control over the surrounding code for crate-exported macros, you should not assume anything about what has been imported at the invocation site.\n\nFor declarative macros, there’s a special, always-present meta-variable called `$crate`, which resolves to the crate that your declarative macro is defined in. So it’s usually prudent to use that as a common reference point for any items needed by your macro’s expansion.\n\n```\n// Example type - pretend we have a full type definition.\npub struct MyCustomHashMap<K, V> {\n    /*...*/\n}\n\n/// A declarative macro that produces a hash map.\n///\n/// Note: Actually, the standard is attempting to add this!\n///       See: https://doc.rust-lang.org/stable/std/macro.hash_map.html\n#[macro_export]\nmacro_rules! hash_map {\n    ( $( $key:expr => $value:expr ),* $(,)? ) => {{\n        // Use our hashmap implementation from our crate.\n        let mut map = $crate::MyCustomHashMap::new();\n        $( map.insert($key, $value); )*\n        map\n    }}\n}\n\n#[test]\nfn example() {\n    let map = hash_map! {\n        \"key\" => \"value\",\n    };\n    assert_eq!(map.get(\"key\"), Some(&\"value\"));\n}\n```\n\nIn the above example we demonstrate this with a `MyCustomHashMap` which our crate *also* exports. Other standing functions, or other required traits, would also need to be resolved via `$crate`.\n\nIf your macro depends on items from other crates, it’s often wise to re-export those dependencies in a public module hidden within your crate. We usually name this something like `__private` and mark it `#[doc(hidden)]` to deter usage.\n\n```\n#[doc(hidden)]\npub mod __private {\n    // Publicly re-export things that your macro uses here.\n}\n```\n\nThe [`serde`](https://crates.io/crates/serde) crate does this with its own [`__private`](https://docs.rs/serde/1.0.229/src/serde/core/crate_root.rs.html#158-163) module. Though, their instance of it may be more for their procedural macros (`Serialize` and `Deserialize`). After all, this isn’t a problem specific to declarative macros.\n\n[###](#how-to-organize-declarative-macros)\n\n### How to Organize Declarative Macros\n\nMacros very often don’t have a specific type they’re bound to, usually they’re general convenience macros.\n\nThat being the case, I recommend the following organization strategy:\n\n- For macros which are constrained to a single module or function, **just define them where they’re needed**.\n- For macros which are shared across multiple modules, **define them in a common parent module**.\n  - Tip: For smaller crates, this can often be easiest to target the top-most module (`lib.rs`).\n\nI don’t like to carelessly slap macros into some parent module (or I have several of them, which becomes unwieldy). So I put them in separate files for each macro that I define, and then re-export them into some organizational parent module.\n\nCrate-exported macros fit into this pretty well. In those cases, I just don’t re-export into the parent if the intended way to access the macro is by from the crate root.\n\n> This harkens back to my [module organization article](https://sigseis.dev/articles/2026/06/26), where I detail methods of using “organizational modules”, and defining types in their own separate files.\n>\n> Please take a look at that if you are having trouble understanding my organization strategy.\n\n**mod.rs:** *(organizational module; often `lib.rs`)*\n\n```\nmod macros;\nmod type_a;\nmod type_b;\nmod type_c;\n// etc...\n```\n\n**macros/mod.rs:** *(organizational module)*\n\n```\n// Modules:\nmod exported_macro;\nmod helper_macro_a;\nmod helper_macro_b;\nmod helper_macro_c;\n// etc...\n\n// Re-Exports:\npub(crate) use helper_macro_a::*;\npub(crate) use helper_macro_b::*;\npub(crate) use helper_macro_c::*;\n// etc...\n```\n\n**macros/exported\\_macro.rs:**\n\n```\n// In this case, I'm happy to bind it to the root.\n#[macro_export]\nmacro_rules! exported_macro {\n    () => {};\n}\n```\n\n**macros/helper\\_macro\\_a.rs:**\n\n```\nmacro_rules! helper_macro_a {\n    () => {};\n}\npub(crate) use helper_macro_a;\n```\n\n**Elsewhere in the crate:**\n\n```\n// Either pull them in for usage:\nuse crate::macros::{helper_macro_a, helper_macro_b};\nhelper_macro_a!();\nhelper_macro_b!();\n\n// Or refer to them via absolute paths:\ncrate::macros::helper_macro_c!();\n```\n\nI know this *seems* like overkill, but the nice thing about this is I can always very easily find a macro. Either the macro is defined near its usage (so it’s within the same file), *or* the file is named the same thing as the macro so it’s easy to open via a command.\n\nIf a macro is very closely related to another macro, and they’re only split up for ease of maintenance, I usually put them in the same file. But I only do that if they are meant to be implementation details of the main macro intended to be invoked.\n\nAnd, you don’t always need an organizing `macros` module - you could just re-export the macros right into the main organizational module. That’s for each person and project to decide on.\n\n[##](#use-cases-for-declarative-macros)\n\n## Use Cases for Declarative Macros\n\nNow that we know how to integrate declarative macros into our project, let’s look at some use cases for them.\n\nAt the risk of sounding like a broken record - I would like to remind you to try as hard as possible ***NOT*** to export the macro.\n\nA crate-local macro, as stated, is really nice because users only depend on the side effects of it. You control the syntax and the places it’s invoked completely. There’s less to worry about with respects to breaking changes, or dependencies on unintended usage of the macro.\n\nOnly export a macro if you’re *sure* it’s a wise decision.\n\n[###](#implementing-traits-and-functions)\n\n### Implementing Traits and Functions\n\nWhile developing a crate, you may author types that have some nearly-identically-implemented functions or traits.\n\nIf the types are semantically closely related, we can reduce duplication using a helper macro. The helper macro will implement the common traits or function, with some information provided to it.\n\nSome specific examples of when this is beneficial include:\n\n- If you need to author several types which are mostly simple wrappers of other types (something like a newtype).\n- If you want to ensure several types have an identical subset of an API (functions and traits).\n\nBe careful not to reach for declarative macros at the smallest sign of duplication, though. Instead, you should consider it when things appear to be very cut-and-paste. If you over-generalize, that could make maintenance *more* of a burden, not less.\n\nFor implementation macros like these, I like to follow a `key = value` pattern.\n\n```\nmacro_rules! impl_example {\n    (\n        input_1 = $input_1:literal,\n        input_2 = ($($input_2:tt)*),\n        input_3 = {\n            grouped_input_1 = $grouped_input_1:literal,\n            grouped_input_2 = $grouped_input_2:ident,\n            grouped_input_3 = $grouped_input_3:expr,\n        },\n        input_4 = [$($input_4:expr),* $(,)?],\n    ) => { /*Expansion Here*/ };\n}\n\nimpl_example! {\n    input_1 = 123,\n    input_2 = (complex; grouped, input),\n    input_3 = {\n        grouped_input_1 = \"sample\",\n        grouped_input_2 = Sample,\n        grouped_input_3 = concat!(\"...\"),\n        // ...\n    },\n    input_4 = [\n        array_value_1,\n        array_value_2,\n        array_value_3,\n        // ...\n    ],\n    // ... etc ...\n}\n```\n\nMy reason for preferring this syntax is:\n\n- You cannot accidentally map a fragment to the wrong input without it being visible at the call site.\n- It uses a different binding syntax from struct initialization to distance itself from appearing to initialize an object.\n- Despite the binding syntax being different, it feels familiar enough to be immediately understood.\n\nThough, I’ll admit the last two points aren’t that important. If you feel more comfortable you could use a more “struct field initialization” style format (`key: value`). That’s up to you!\n\n> **Don’t over-generalize these**, accept them in *one* order - we’re only using these internally after all.\n>\n> I sometimes like to order them alphanumerically by key name, so that the order is at least consistent.\n\n**Examples**\n\nAn example of this in the wild are the integer types in the Rust language itself. Integer types (like [`u8`](https://doc.rust-lang.org/1.99.1/src/core/num/mod.rs.html#586-614)) use a crate-local [`int_impl`](https://doc.rust-lang.org/1.99.1/src/core/num/int_macros.rs.html) macro to implement common functions and traits.\n\nIt’s also common to use declarative macros to assist in implementing a trait across tuples of different arities. Commonly useful in cases where your trait will just call the same trait on all tuple elements. You can see an example of this in the [`serde`](https://crates.io/crates/serde) crate with the crate-local [`tuple_impls!`](https://docs.rs/serde/1.0.229/src/serde/core/ser/impls.rs.html#404-420) macro.\n\nIf you’d like a toy example - here’s one using some strongly typed time values. The macro helps us ensure the conversion implementations are consistent between the different types.\n\n```\n#[derive(Copy, Clone, Debug, PartialEq)]\npub struct OverflowError;\n\n#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\npub struct Hours(u32);\n\n#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\npub struct Minutes(u32);\n\n#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\npub struct Seconds(u32);\n\nmacro_rules! impl_time_functionality {\n    (\n        from = [$($from:ty),* $(,)?],\n        seconds_per = $seconds_per:expr,\n        try_from = [$($try_from:ty),* $(,)?],\n        type = $type:ty,\n    ) => {\n        // Ensure that we have common functions that we expect all of these time types to have.\n        //\n        // Reminder that you can open multiple impl blocks for a single type, so if there are\n        // functions that don't make sense to be commonly implemented here, then just write them\n        // in a separate impl block for the intended type outside of this macro.\n        impl $type {\n            // Helper constant to facilitate conversion impls.\n            // We don't want to export it publicly from this case.\n            pub(crate) const SECONDS_PER: u32 = $seconds_per;\n\n            pub fn to_u32(self) -> u32 {\n                self.0\n            }\n        }\n\n        $(\n            impl TryFrom<$try_from> for $type {\n                type Error = OverflowError;\n                fn try_from(value: $try_from) -> Result<Self, Self::Error> {\n                    // This const assert ensures we haven't used the helper macro improperly.\n                    const _: () = assert!(\n                        <$try_from>::SECONDS_PER > $seconds_per,\n                        concat!(stringify!($try_from), \" must contain more seconds than \", stringify!($type)),\n                    );\n                    Ok(Self(value.to_u32()\n                        .checked_mul(<$try_from>::SECONDS_PER / Self::SECONDS_PER)\n                        .ok_or(OverflowError)?))\n                }\n            }\n        )*\n\n        $(\n            impl From<$from> for $type {\n                fn from(value: $from) -> Self {\n                    // This const assert ensures we haven't used the helper macro improperly.\n                    const _: () = assert!(\n                        <$from>::SECONDS_PER < $seconds_per,\n                        concat!(stringify!($from), \" must contain fewer seconds than \", stringify!($type)),\n                    );\n                    Self(value.to_u32() / (Self::SECONDS_PER / <$from>::SECONDS_PER))\n                }\n            }\n        )*\n    };\n}\n\nimpl_time_functionality! {\n    from = [],\n    seconds_per = 1,\n    try_from = [ Minutes, Hours ],\n    type = Seconds,\n}\n\nimpl_time_functionality! {\n    from = [ Seconds ],\n    seconds_per = 60,\n    try_from = [ Hours ],\n    type = Minutes,\n}\n\nimpl_time_functionality! {\n    from = [ Seconds, Minutes ],\n    seconds_per = 60 * 60,\n    try_from = [],\n    type = Hours,\n}\n\n#[test]\nfn test() {\n    assert_eq!(Hours::from(Seconds(60 * 60)), Hours(1));\n    assert_eq!(Minutes::from(Seconds(60 * 60)), Minutes(60));\n    assert_eq!(Seconds::from(Seconds(60 * 60)), Seconds(60 * 60));\n    assert_eq!(Hours::from(Minutes(60)), Hours(1));\n    assert_eq!(Minutes::from(Minutes(60)), Minutes(60));\n    assert_eq!(Seconds::try_from(Minutes(60)), Ok(Seconds(60 * 60)));\n    assert_eq!(Hours::from(Hours(1)), Hours(1));\n    assert_eq!(Minutes::try_from(Hours(1)), Ok(Minutes(60)));\n    assert_eq!(Seconds::try_from(Hours(1)), Ok(Seconds(60 * 60)));\n}\n```\n\n> Sometimes the deduplication is not worth the obfuscation that it creates, but that’s a case-by-case thing. For simple types like this (and the integer types from the standard library), the benefit is clear, as it produces the obvious intended end result and ensures the APIs are all implemented uniformly.\n>\n> If you find yourself adding a lot of special-casing and splitting your macro into many separate macros, that might be a sign that you’ve attempted to use this pattern in a place where it’s not helpful.\n>\n> In those cases, it’s probably best to just write out all your traits and impls by-hand, even if it results in some duplication.\n\n[###](#format-like-expressions)\n\n### `format!`-Like Expressions\n\nA really popular reason for declarative macros is to match the [`format!`](https://doc.rust-lang.org/stable/std/macro.format.html) syntax from the standard library.\n\nYou don’t always need to provide such a macro, sometimes you can just take `impl Into<String>` and let the user format as they please. But it can make things more readable in cases where the user will *always* be formatting a string, or if you want formatting to be conditionally compiled-out when disabling `alloc` support.\n\n**Examples**\n\nTo point at the standard library again, we can look at the [`todo!`](https://doc.rust-lang.org/1.99.1/src/core/macros/mod.rs.html#884-891) macro. It’s simple enough that it’s just implemented right there as a declarative macro instead of being a built-in like many other macros (similar to [`assert_eq!`](https://doc.rust-lang.org/1.99.1/src/core/macros/mod.rs.html#43-70), [`matches!`](https://doc.rust-lang.org/1.99.1/src/core/macros/mod.rs.html#431-439), and a few others).\n\nIt’s a bit of a low-hanging fruit, but the [`log`](https://crates.io/crates/log) crate has some pretty obvious examples; [`info!`](https://docs.rs/log/0.4.34/src/log/macros.rs.html#252-273), [`warn!`](https://docs.rs/log/0.4.34/src/log/macros.rs.html#204-225), and [`error!`](https://docs.rs/log/0.4.34/src/log/macros.rs.html#165-186). In general, anything with a `format!`-like operation benefits from a declarative macro.\n\n`assert!`-like macros are another example of this kind of macro. You may not think too much about it, but it can be nice to provide added details about a failure for unit tests. The `assert!` macros all accept format arguments at the end, and you can too if you need some adapter `assert!` macro.\n\n```\nmacro_rules! assert_in_range {\n    ($input:expr, $low:expr, $high:expr, $($msg:tt)*) => {{\n        let input = $input;\n        let low = $low;\n        let high = $high;\n        assert!(\n            input >= $low,\n            \"{}: range check failed: {input} >= {low}\",\n            format_args!($($msg)*),\n        );\n        assert!(\n            input <= $high,\n            \"{}: range check failed: {input} <= {high}\",\n            format_args!($($msg)*),\n        );\n    }};\n}\n\n#[test]\nfn example() {\n    let number = 5;\n    assert_in_range!(number, 50, 100, \"formatted example (input={})\", number);\n}\n```\n\nThe failure here looks like this:\n\n```\nthread 'example' (50) panicked at src/lib.rs:22:5:\nformatted example (input=5): range check failed: 5 >= 50\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\n\n[###](#used-for-initializing-complex-types)\n\n### Used for Initializing Complex Types\n\nFor many types, you can get away with either the struct initialization format, or using the builder pattern.\n\n```\n#[derive(Default)]\nstruct Example {\n    foo: u8,\n    bar: String,\n    baz: bool,\n}\n\n// Some initialization patterns:\nfn struct_initialization() {\n    let object = Example {\n        foo: 0,\n        bar: format!(\"example formatted string\"),\n        baz: false,\n    };\n}\n\nfn struct_initialization_partial() {\n    let object = Example {\n        bar: format!(\"example formatted string\"),\n        ..Example::default()\n    };\n}\n\nfn builder_pattern() {\n    // `ExampleBuilder` type not shown for brevity.\n    let object = ExampleBuilder::default()\n        .with_foo(123)\n        .with_bar(format!(\"example formatted string\"))\n        .finish();\n}\n```\n\nBut sometimes we want a different syntax than this, for readability reasons.\n\nOften custom syntaxes are only beneficial if there’s some common, well-accepted, pre-existing format (e.g. an existing data markup language, like JSON). But occasionally a purely custom syntax can be helpful.\n\nContainers are a great example of custom initialization syntax that everyone should have some experience with.\n\nIt’s true you can (and should) implement [`FromIterator`](https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html) to initialize from some sequence of elements. But this syntax can be awkward for explicit initialization that isn’t coming from some already constructed values. So for developer convenience we often create small helper macros to improve readability.\n\nLike with many things relating to macros, only add them when you’re sure they’re useful. Think about whether the pre-existing methods for initializing objects is good enough.\n\n**Examples**\n\nIt should go without saying, but the [`vec!`](https://doc.rust-lang.org/stable/std/macro.vec.html) macro is a really popular example of this. And soon we will have yet another version of this, with the [`hash_map!`](https://doc.rust-lang.org/stable/std/macro.hash_map.html) macro.\n\nThe best example of this I can think of for object initialization is the [`json!`](https://docs.rs/serde_json/latest/serde_json/macro.json.html) macro from the `serde_json` crate.\n\nThis is actually a good example of using declarative macros to do something non-trivial. Specifically, note that they hide the implementation details of the macro by splitting it into multiple macros, [`json!`](https://docs.rs/serde_json/1.0.154/src/serde_json/macros.rs.html#54-59) is the main one you call, and it redirects to another exported macro which is hidden from documentation called [`json_internal`](https://docs.rs/serde_json/1.0.154/src/serde_json/macros.rs.html#68-281).\n\nThough, I will admit, `json!` is one of those declarative macros I think is teetering on the edge of “should have been a procedural macro”. Though, it might be hard to safely change it over at this point.\n\n[###](#reducing-boilerplate)\n\n### Reducing Boilerplate\n\nSometimes you find yourself writing many similar lines of code within a small set of functions.\n\nIn most cases, it’s best to just change these into helper functions and let the compiler optimize things. But sometimes you’ll run into situations where you can’t do that.\n\n- You need to generate a distinct *type* per functional configuration (e.g. not just logic or impls).\n- You’re using it to provide the body of a function that the macro is implementing, and you can’t generalize this function body over any trait bounds.\n- When your macro influences the surrounding control flow (`break`, `continue`, `return`).\n- For optimization reasons (which you have surely bench tested).\n\n**Be careful when altering control flow.**\n\nIt can have some utility for really simple, localized helper macros. But I tend to consider it to be an anti-pattern to *export* such macros. However, used very sparingly, in unique cases to assist in implementing something, it can be helpful.\n\nHonestly, I even lean away from it for crate-local macros as well. Obfuscating the control flow negatively impacts readability in my experience.\n\n**Examples**\n\nOne example where this pattern being used for optimization reasons is within the Rust standard library. The `str` type specializes based on string lengths for optimization reasons ([`specialize_for_lengths`](https://doc.rust-lang.org/1.99.1/src/alloc/str.rs.html#81-109); used [here](https://doc.rust-lang.org/1.99.1/src/alloc/str.rs.html#200)).\n\nThe [`bytes`](https://crates.io/crates/bytes) crate actually uses some macros to reduce code duplication. See the crate-local [`buf_get_impl`](https://docs.rs/bytes/1.12.1/src/bytes/buf/buf_impl.rs.html#72-85) macro. This is a good example of the macro providing a common implementation for a set functions. The functions that are being implemented simply invoke the macro to expand this common implementation.\n\nAn example of a crate-exported macro used to produce new types can be found in the [`bitflags`](https://crates.io/crates/bitflags) crate. In this case, it uses some custom syntax that looks kind of like regular Rust code, so it’s a good reference for how to use some different fragment specifiers (like `meta` or `vis`).\n\nFinally, probably one of the most popular control-flow-impacting macros, is anyhow’s [`bail!`](https://docs.rs/anyhow/latest/anyhow/macro.bail.html) macro. As mentioned, I’m not a fan of these kinds of macros (including this one). But I want to mention it anyway, since it fits within this set of example use-cases, and likely has some popularity. (Another potential example of this is the standard library’s [`ready!`](https://doc.rust-lang.org/nightly/core/task/macro.ready.html) macro for polling futures.)\n\nA really simple example of this is constructing a newtype that redirects to the underlying implementation. We may want to ensure that the types are actually distinct from one another, but we may not want to re-implement the functionality the type provides ([`impl_displayable_type`](https://docs.rs/typed-ident/0.0.3/src/typed_ident/core/fmt/macros/impl_displayable_type.rs.html) - example usage [here](https://docs.rs/typed-ident/0.0.3/src/typed_ident/core/fmt/bounded/as_lower_camel.rs.html#15-54) - is an example of this from one of my own crates, [`typed-ident`](https://crates.io/crates/typed-ident)).\n\n```\n// A simplified form of `impl_displayable_type` to use as an example.\nmacro_rules! impl_displayable_type {\n    (\n        name=$name:ident,\n        over=$over:ident,\n        docs=$docs:expr,\n    ) => {\n        #[doc = $docs]\n        pub struct $name($over);\n\n        impl core::fmt::Display for $name {\n            #[inline]\n            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n                self.0.fmt(f)\n            }\n        }\n    };\n}\n\n// We have some displayable types that we don't want to conflate.\n\nimpl_displayable_type! {\n    name = ObjectId,\n    over = u64,\n    docs = \"Example documentation here\",\n}\n\nimpl_displayable_type! {\n    name = GroupId,\n    over = u64,\n    docs = concat!(\n        \"`docs` is an expression so you can do things like this.\\n\",\n        \"\\n\",\n        \"Multi-line documentation, for better readability!\",\n    ),\n}\n\n// So now, if we have an API like this...\nstruct Object;\nimpl Object {\n    pub fn object_id(&self) -> ObjectId {\n        todo!()\n    }\n    pub fn group_id(&self) -> GroupId {\n        todo!()\n    }\n}\n\n// ... You can't accidentally do something like this.\nfn example_bad_usage_that_no_longer_compiles(object: Object) {\n    let group_id: GroupId = object.object_id(); // Fails to compile!\n}\n```\n\n> It can be tempting to use declarative macros in places where a `#[derive(...)]` procedural macro would make more sense. Try to avoid creating such macros unless necessary.\n>\n> A common toy example for declarative macros is to create a function on enums so you can get static strings of the enum variant names. But this can be accomplished through a derive macro, and that feels more idiomatic to me (like [`IntoStaticStr`](https://docs.rs/strum/latest/strum/derive.IntoStaticStr.html) from the [`strum`](https://crates.io/crates/strum) crate, or - maybe better - having a custom trait to represent this).\n>\n> **Do what you believe the end-user would find most natural.** If what your macro is doing is implementing a trait - you probably ought to make it a derive macro unless you have good reason not to.\n>\n> We’ll talk more about derive macros when we cover procedural macros in a later article, though.\n\n[##](#summary)\n\n## Summary\n\n**Thanks for reading!**\n\nMacros are a really complex topic, so thanks for sticking with me through these articles as I try to explain them.\n\nIf you were able to learn something new, and want to show your gratitude, please consider [**sending a donation on Ko-Fi**](https://ko-fi.com/sigseis)!\n\nI’d love to be able to work with the community full-time, and support like that will allow me to continue writing articles like these.\n\nIn this article, we:\n\n- Learned about macro scoping, and how to export declarative macros.\n- Learned a method for organizing declarative macros for ease of maintenance.\n- Explored a small selection of use cases for declarative macros.\n- Saw some examples of declarative macro usage (some real-world, and other toy examples).\n\nI still have a little more to say about declarative macros…\n\nThe original draft of this article was 7500 words, and that’s too long. The next article will focus on best practices, and common pain points with declarative macros. Please look forward to it!\n\nI promise we’ll get to procedural macros eventually. :)\n","body_html":"<h1 id=\"rust-declarative-macros-organization-scoping-and-common-use-case\">Rust Declarative Macros: Organization, Scoping, and Common Use-Cases</h1>\n<figure><img src=\"https://sigseis.dev/articles/2026/11/10/cover.280896d925.picture/cover.jpg\" alt=\"An Oguri Cap toy from Umamusume standing in front of a fruit market set, holding a mango with a happy expression on her face.\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>In our <a href=\"https://sigseis.dev/articles/2026/10/06\" rel=\"nofollow ugc noopener\">previous article</a>, we covered what declarative macros are, and how to define and use them.</p>\n<p>In this article, we will focus on how to integrate them into your crate. That means we’ll cover macro scoping, organization, and exporting. We’ll also take a look at some common use-cases with examples.</p>\n<p>Hopefully, after reading these two articles, you’ll feel ready to start experimenting with declarative macros in your own crates!</p>\n<blockquote><p>This article is tested under the 2024 edition of Rust.</p>\n<p>For older code you may see some older patterns, like using a lot of <code>#[macro_use]</code> statements, but this article is going to focus on more modern practices. If something doesn’t compile for you, check your Rust version and edition.</p></blockquote>\n<p><a href=\"#article-toc\">##</a></p>\n<h2 id=\"table-of-contents\">Table of Contents</h2>\n<ul><li><a href=\"#how-to-integrate-declarative-macros-into-your-crate\">How To Integrate Declarative Macros Into Your Crate</a><ul><li><a href=\"#scoping-rules-for-declarative-macros\">Scoping Rules for Declarative Macros</a><ul><li><a href=\"#textual-scoping-rules\">Textual Scoping Rules</a></li><li><a href=\"#path-based-scoping-rules\">Path-Based Scoping Rules</a></li></ul></li><li><a href=\"#exporting-declarative-macros\">Exporting Declarative Macros</a></li><li><a href=\"#a-reminder-about-macro-hygiene\">A Reminder About Macro Hygiene</a></li><li><a href=\"#how-to-organize-declarative-macros\">How to Organize Declarative Macros</a></li></ul></li><li><a href=\"#use-cases-for-declarative-macros\">Use Cases for Declarative Macros</a><ul><li><a href=\"#implementing-traits-and-functions\">Implementing Traits and Functions</a></li><li><a href=\"#format-like-expressions\"><code>format!</code>-Like Expressions</a></li><li><a href=\"#used-for-initializing-complex-types\">Used for Initializing Complex Types</a></li><li><a href=\"#reducing-boilerplate\">Reducing Boilerplate</a></li></ul></li><li><a href=\"#summary\">Summary</a></li></ul>\n<p><a href=\"#how-to-integrate-declarative-macros-into-your-crate\">##</a></p>\n<h2 id=\"how-to-integrate-declarative-macros-into-your-crate\">How To Integrate Declarative Macros Into Your Crate</h2>\n<p>Broadly speaking, I like to differentiate declarative macros based on access level.</p>\n<ul><li><strong>crate-exported</strong>: Intended to be exported from your crate and used by your dependents</li><li><strong>crate-local</strong>: Intended to be used privately within your crate</li></ul>\n<p><strong>You should prefer to keep macros crate-local if possible.</strong></p>\n<p>Macros can be useful even if you don’t intend on exporting them. Actually, that’s most commonly how I make use of macros!</p>\n<p>The main way to differentiate between the two is whether a macro is marked with the <code>#[macro_export]</code> attribute. If not, then it’s a <strong>crate-local</strong> macro.</p>\n<p><a href=\"#scoping-rules-for-declarative-macros\">###</a></p>\n<h3 id=\"scoping-rules-for-declarative-macros\">Scoping Rules for Declarative Macros</h3>\n<p>For historic reasons, macros have two different ways they scope into the surrounding code.</p>\n<ul><li><strong>Textual Scoping</strong>: The macro scope is based on <em>where in the file it’s defined</em></li><li><strong>Path-Based Scoping</strong>: The macro becomes an item in the module tree (acting more similarly to a standard Rust item)</li></ul>\n<p>Where possible, you should prefer <em>path-based scoping</em>, but textual scoping can come in handy in some cases. Additionally, you’re very likely to run into heavy usage of the original textual scoping rules. So it’s worth understanding them regardless.</p>\n<p><a href=\"#textual-scoping-rules\">####</a></p>\n<h4 id=\"textual-scoping-rules\">Textual Scoping Rules</h4>\n<p><strong>By default, declarative macros take on a textual scope.</strong></p>\n<p>Textual scoped declarative macros have some counter-intuitive visibility and access rules.</p>\n<ul><li>The macro may be used ONLY <em>after</em> its definition within a module, function, or logical scope.</li><li>The macro may be used by any submodules after the macro definition, <em>even without importing it explicitly</em>.</li></ul>\n<p>So unlike other parts of the Rust language, <strong>order actually matters for textual scoped declarative macros</strong>.</p>\n<p>The most narrow visibility is within a logical scope (for example a function). Sometimes, though admittedly rarely, this can be useful for functions that have a lot of internal repetition.</p>\n<pre><code>fn example() {\n    macro_rules! helper_macro {\n        () =&gt; {};\n    }\n    helper_macro!();\n}\n\n// You cannot access this macro outside of the function.</code></pre>\n<p>If the macro is going to be used in multiple items within the same module, you can simply define it in the module itself. This is more visible than within a single function, but it’s still constrained to only the current module and its submodules.</p>\n<pre><code>// You cannot use it here, because it&#39;s not defined yet.\n\nmacro_rules! helper_macro {\n    () =&gt; {};\n}\n\n// Now it can be invoked and used.\nhelper_macro!();\n\n// It can be used within functions, as one might expect.\nfn within_functions() {\n    helper_macro!();\n}\n\n// Works within submodules of any depth as well,\n// which might feel counter-intuitive.\nmod even_within_submodules {\n    helper_macro!();\n}</code></pre>\n<p>Sometimes it can be beneficial to use a macro from the <em>parent</em> module the containing module is defined under.</p>\n<p><strong>Modern Rust syntax allows for this better with path-based scoping</strong>, which we’ll learn about in the next section.</p>\n<p>That said, you may still run into this syntax, so we should cover it.</p>\n<p>To hoist macros defined in a submodule into the parent’s textual scope, you can attach the <code>#[macro_use]</code> attribute on the containing module.</p>\n<pre><code>// We still cannot use `helper_macro!` here, it isn&#39;t defined yet.\n\n// After the module definition completes,\n// it&#39;s now defined in the parent&#39;s textual scope.\n#[macro_use]\nmod submodule {\n    macro_rules! helper_macro {\n        () =&gt; {};\n    }\n    helper_macro!();\n}\n\n// See? Now we can access and use it here even without an import.\n// It acts as-if we had defined textually after `submodule`.\nhelper_macro!();\n\n// Works within submodules of any depth as well,\n// since it&#39;s a part of the textual scope.\nmod sibling_submodule {\n    helper_macro!();\n}</code></pre>\n<p>But note that <code>#[macro_use]</code> will not automatically propagate further up the module tree.</p>\n<p>If you want your macro to continue to be defined all the way up the module tree, you’ll have to continue to attach the <code>#[macro_use]</code> attribute on all the parent modules.</p>\n<pre><code>#[macro_use] // &lt;- Necessary if you need it...\nmod outer_file {\n    #[macro_use]\n    mod other_file {\n        macro_rules! helper_macro {\n            () =&gt; {};\n        }\n        helper_macro!();\n    }\n    helper_macro!();\n}\nhelper_macro!(); // &lt;- ... at this location onwards.</code></pre>\n<blockquote><p>Historically, <code>#[macro_use]</code> was also used to import external macros from other crates into your textual scope.</p>\n<p>You should not be doing this anymore for macros imported from other crates, however.</p></blockquote>\n<p><a href=\"#path-based-scoping-rules\">####</a></p>\n<h4 id=\"path-based-scoping-rules\">Path-Based Scoping Rules</h4>\n<p>Path-based scoping for declarative macros allows us to work with macros in a way which feels more idiomatic.</p>\n<ul><li>The macro works a lot like any other item, and can be invoked before the definition.</li><li>In order to be used, it needs to be manually imported or resolved from the module tree.</li></ul>\n<p>This can be accomplished with a small bit of code right after the macro definition:</p>\n<pre><code>macro_rules! helper_macro {\n    () =&gt; {};\n}\n\n// Re-export as an item in the module tree.\npub(crate) use helper_macro;</code></pre>\n<p>When you do this, since the macro is now a part of the module tree, order no longer matters.</p>\n<pre><code>// Can call here, even if the macro isn&#39;t defined yet.\nhelper_macro!();\n\nmacro_rules! helper_macro {\n    () =&gt; {};\n}\npub(crate) use helper_macro;\n\n// Can obviously still call here.\nhelper_macro!();</code></pre>\n<blockquote><p>Even though you can refer to macros out of order when they use path-based scoping, you’ll probably still want to define them before they’re used within the same file. Not because it’s necessary, but because it’s readable!</p></blockquote>\n<p>The real benefit of this is that other modules can import and use the macro like they would any other item.</p>\n<pre><code>mod submodule {\n    macro_rules! helper_macro {\n        () =&gt; {};\n    }\n    pub(crate) use helper_macro;\n}\n\nmod another_submodule {\n    // You can use it like a normal item!\n    use crate::submodule::helper_macro;\n    helper_macro!();\n\n    // Or you can refer to it by a path!\n    crate::submodule::helper_macro!();\n}</code></pre>\n<p>It’s most common to see this used with <code>pub(crate)</code>, but you can really use all item visibilities here (<code>pub(super)</code>, <code>pub(in some::path)</code>, <em>empty for private</em>). <code>pub</code> has some strange properties, however - we’ll cover that in the next section.</p>\n<p><a href=\"#exporting-declarative-macros\">###</a></p>\n<h3 id=\"exporting-declarative-macros\">Exporting Declarative Macros</h3>\n<p>If you want a declarative macro to be usable from outside your crate, you have to attach the <code>#[macro_export]</code> attribute to it.</p>\n<p><strong>Be careful when deciding to export a macro!</strong></p>\n<p>After you export a macro, users may grow to depend on it, and it may become difficult to change or maintain. This is why I usually err towards <em>not</em> exporting a macro, until I’m <em>sure</em> it’s warranted.</p>\n<p>Still, if you’re sure it’s the right thing to do, you can accomplish it like so:</p>\n<pre><code>#[macro_export]\nmacro_rules! exported_macro {\n    () =&gt; {};\n}\n\nmod submodule {\n    use crate::exported_macro;\n    exported_macro!();\n}</code></pre>\n<p>The observable effects of this attribute are:</p>\n<ul><li>The root of your crate will publicly export the macro for dependents to use (<code>use your_crate::exported_macro</code>).</li><li>You can privately import the macro using normal path-based scoping (<code>use crate::exported_macro</code>).</li></ul>\n<p>It doesn’t matter whether the macro is in a submodule or not, it will <em>always</em> export at the root.</p>\n<pre><code>exported_macro!(); // &lt;- Works because of `#[macro_export]`\nmod module {\n    use crate::exported_macro;\n\n    exported_macro!(); // &lt;- Works because of the `use` statement\n    mod submodule {\n        #[macro_export]\n        macro_rules! exported_macro {\n            () =&gt; {};\n        }\n    }\n    exported_macro!(); // &lt;- Works because of the `use` statement\n}\nexported_macro!(); // &lt;- Works because of `#[macro_export]`</code></pre>\n<p>The <code>#[macro_use]</code> attribute still has an effect privately within your crate, as one would expect for textual scoping rules. Though, I don’t recommend using it on modules containing exported macros, instead just go through the exported path.</p>\n<pre><code>exported_macro!(); // &lt;- Works because of `#[macro_export]`\nmod module {\n    // &lt;- Would not be usable here without a `use` statement\n\n    #[macro_use]\n    mod submodule {\n        #[macro_export]\n        macro_rules! exported_macro {\n            () =&gt; {};\n        }\n    }\n    exported_macro!(); // &lt;- Works because of `#[macro_use]`\n}\nexported_macro!(); // &lt;- Works because of `#[macro_export]`</code></pre>\n<p>If you want to export a macro somewhere <em>other</em> than the crate root, there’s a way to allow for that.</p>\n<p>It would be nice if you could just not use <code>#[macro_export]</code>, and instead <code>pub use exported_macro</code>, but as for now this doesn’t work. If you try it, you will be met with a compile error that the macro is “only public within the crate, and cannot be re-exported”.</p>\n<p>So, you <em>MUST</em> use <code>#[macro_export]</code> on exported macros. Then, you can bind that exported macro to a specific location in the module tree with <code>pub use exported_macro</code>.</p>\n<p>That’s annoying since it’ll publish a macro in the root (which you probably don’t intend), so the general pattern for this is:</p>\n<ol><li>Hide the publicly exported macro (so folks can’t see it’s actually at the root).</li><li>Create a public path binding in the module where you want the macro to be accessed from.</li></ol>\n<p>So, for instance:</p>\n<pre><code>pub mod submodule {\n    // Since this is `#[macro_export]`,\n    // it will still wind up at the crate root.\n    //\n    // Because of that, we name this in a way that deters usage.\n    // We&#39;ll also hide it, so that it doesn&#39;t appear in docs.\n    #[doc(hidden)]\n    #[macro_export]\n    macro_rules! __exported_macro {\n        () =&gt; {};\n    }\n\n    /// The actual documentation will go here!\n    #[doc(inline)]\n    pub use __exported_macro as exported_macro;\n}\n\n// Technically this does export the following macro...\ncrate::__exported_macro!();\n\n// However, documentation will only list this version.\n// And, this version will be public for dependents to use.\ncrate::submodule::exported_macro!();</code></pre>\n<blockquote><p>In future versions of Rust, this cruft around visibility and module tree exporting may get cleaned up.</p>\n<p>It’s hard to make changes like this to the Rust language that won’t break existing code. So this has remained one of those weird parts of the language which - if you’re not careful - can work in odd, non-idiomatic ways.</p>\n<p>There’s a pretty in-depth thread about this <a href=\"https://internals.rust-lang.org/t/pub-on-macro-rules/19358\" rel=\"nofollow ugc noopener\">here</a> on the Rust internals forum.</p></blockquote>\n<p><a href=\"#a-reminder-about-macro-hygiene\">###</a></p>\n<h3 id=\"a-reminder-about-macro-hygiene\">A Reminder About Macro Hygiene</h3>\n<p>Recall from our prior article, when we talked about <a href=\"https://sigseis.dev/articles/2026/10/06#what-s-this-macro-hygiene-thing\" rel=\"nofollow ugc noopener\">macro hygiene</a>, that Rust uses what’s known as “mixed-site hygiene”.</p>\n<p>Most items - other than local variables - are resolved from where the macro is invoked (functions, types, traits, etc.). For crate-local macros, you can be a little looser with this and require that the invoking code imports some items as needed to compile. But for crate-exported macros, it’s not a good idea to force the user to do this.</p>\n<p>Because of that, you should keep the following things in mind:</p>\n<ul><li>You usually want to avoid using the <code>crate</code> keyword directly, because it may not refer to <em>your</em> crate.</li><li>Since you’re in less control over the surrounding code for crate-exported macros, you should not assume anything about what has been imported at the invocation site.</li></ul>\n<p>For declarative macros, there’s a special, always-present meta-variable called <code>$crate</code>, which resolves to the crate that your declarative macro is defined in. So it’s usually prudent to use that as a common reference point for any items needed by your macro’s expansion.</p>\n<pre><code>// Example type - pretend we have a full type definition.\npub struct MyCustomHashMap&lt;K, V&gt; {\n    /*...*/\n}\n\n/// A declarative macro that produces a hash map.\n///\n/// Note: Actually, the standard is attempting to add this!\n///       See: https://doc.rust-lang.org/stable/std/macro.hash_map.html\n#[macro_export]\nmacro_rules! hash_map {\n    ( $( $key:expr =&gt; $value:expr ),* $(,)? ) =&gt; {{\n        // Use our hashmap implementation from our crate.\n        let mut map = $crate::MyCustomHashMap::new();\n        $( map.insert($key, $value); )*\n        map\n    }}\n}\n\n#[test]\nfn example() {\n    let map = hash_map! {\n        &quot;key&quot; =&gt; &quot;value&quot;,\n    };\n    assert_eq!(map.get(&quot;key&quot;), Some(&amp;&quot;value&quot;));\n}</code></pre>\n<p>In the above example we demonstrate this with a <code>MyCustomHashMap</code> which our crate <em>also</em> exports. Other standing functions, or other required traits, would also need to be resolved via <code>$crate</code>.</p>\n<p>If your macro depends on items from other crates, it’s often wise to re-export those dependencies in a public module hidden within your crate. We usually name this something like <code>__private</code> and mark it <code>#[doc(hidden)]</code> to deter usage.</p>\n<pre><code>#[doc(hidden)]\npub mod __private {\n    // Publicly re-export things that your macro uses here.\n}</code></pre>\n<p>The <a href=\"https://crates.io/crates/serde\" rel=\"nofollow ugc noopener\"><code>serde</code></a> crate does this with its own <a href=\"https://docs.rs/serde/1.0.229/src/serde/core/crate_root.rs.html#158-163\" rel=\"nofollow ugc noopener\"><code>__private</code></a> module. Though, their instance of it may be more for their procedural macros (<code>Serialize</code> and <code>Deserialize</code>). After all, this isn’t a problem specific to declarative macros.</p>\n<p><a href=\"#how-to-organize-declarative-macros\">###</a></p>\n<h3 id=\"how-to-organize-declarative-macros\">How to Organize Declarative Macros</h3>\n<p>Macros very often don’t have a specific type they’re bound to, usually they’re general convenience macros.</p>\n<p>That being the case, I recommend the following organization strategy:</p>\n<ul><li>For macros which are constrained to a single module or function, <strong>just define them where they’re needed</strong>.</li><li>For macros which are shared across multiple modules, <strong>define them in a common parent module</strong>.<ul><li>Tip: For smaller crates, this can often be easiest to target the top-most module (<code>lib.rs</code>).</li></ul></li></ul>\n<p>I don’t like to carelessly slap macros into some parent module (or I have several of them, which becomes unwieldy). So I put them in separate files for each macro that I define, and then re-export them into some organizational parent module.</p>\n<p>Crate-exported macros fit into this pretty well. In those cases, I just don’t re-export into the parent if the intended way to access the macro is by from the crate root.</p>\n<blockquote><p>This harkens back to my <a href=\"https://sigseis.dev/articles/2026/06/26\" rel=\"nofollow ugc noopener\">module organization article</a>, where I detail methods of using “organizational modules”, and defining types in their own separate files.</p>\n<p>Please take a look at that if you are having trouble understanding my organization strategy.</p></blockquote>\n<p><strong>mod.rs:</strong> <em>(organizational module; often <code>lib.rs</code>)</em></p>\n<pre><code>mod macros;\nmod type_a;\nmod type_b;\nmod type_c;\n// etc...</code></pre>\n<p><strong>macros/mod.rs:</strong> <em>(organizational module)</em></p>\n<pre><code>// Modules:\nmod exported_macro;\nmod helper_macro_a;\nmod helper_macro_b;\nmod helper_macro_c;\n// etc...\n\n// Re-Exports:\npub(crate) use helper_macro_a::*;\npub(crate) use helper_macro_b::*;\npub(crate) use helper_macro_c::*;\n// etc...</code></pre>\n<p><strong>macros/exported_macro.rs:</strong></p>\n<pre><code>// In this case, I&#39;m happy to bind it to the root.\n#[macro_export]\nmacro_rules! exported_macro {\n    () =&gt; {};\n}</code></pre>\n<p><strong>macros/helper_macro_a.rs:</strong></p>\n<pre><code>macro_rules! helper_macro_a {\n    () =&gt; {};\n}\npub(crate) use helper_macro_a;</code></pre>\n<p><strong>Elsewhere in the crate:</strong></p>\n<pre><code>// Either pull them in for usage:\nuse crate::macros::{helper_macro_a, helper_macro_b};\nhelper_macro_a!();\nhelper_macro_b!();\n\n// Or refer to them via absolute paths:\ncrate::macros::helper_macro_c!();</code></pre>\n<p>I know this <em>seems</em> like overkill, but the nice thing about this is I can always very easily find a macro. Either the macro is defined near its usage (so it’s within the same file), <em>or</em> the file is named the same thing as the macro so it’s easy to open via a command.</p>\n<p>If a macro is very closely related to another macro, and they’re only split up for ease of maintenance, I usually put them in the same file. But I only do that if they are meant to be implementation details of the main macro intended to be invoked.</p>\n<p>And, you don’t always need an organizing <code>macros</code> module - you could just re-export the macros right into the main organizational module. That’s for each person and project to decide on.</p>\n<p><a href=\"#use-cases-for-declarative-macros\">##</a></p>\n<h2 id=\"use-cases-for-declarative-macros\">Use Cases for Declarative Macros</h2>\n<p>Now that we know how to integrate declarative macros into our project, let’s look at some use cases for them.</p>\n<p>At the risk of sounding like a broken record - I would like to remind you to try as hard as possible <strong><em>NOT</em></strong> to export the macro.</p>\n<p>A crate-local macro, as stated, is really nice because users only depend on the side effects of it. You control the syntax and the places it’s invoked completely. There’s less to worry about with respects to breaking changes, or dependencies on unintended usage of the macro.</p>\n<p>Only export a macro if you’re <em>sure</em> it’s a wise decision.</p>\n<p><a href=\"#implementing-traits-and-functions\">###</a></p>\n<h3 id=\"implementing-traits-and-functions\">Implementing Traits and Functions</h3>\n<p>While developing a crate, you may author types that have some nearly-identically-implemented functions or traits.</p>\n<p>If the types are semantically closely related, we can reduce duplication using a helper macro. The helper macro will implement the common traits or function, with some information provided to it.</p>\n<p>Some specific examples of when this is beneficial include:</p>\n<ul><li>If you need to author several types which are mostly simple wrappers of other types (something like a newtype).</li><li>If you want to ensure several types have an identical subset of an API (functions and traits).</li></ul>\n<p>Be careful not to reach for declarative macros at the smallest sign of duplication, though. Instead, you should consider it when things appear to be very cut-and-paste. If you over-generalize, that could make maintenance <em>more</em> of a burden, not less.</p>\n<p>For implementation macros like these, I like to follow a <code>key = value</code> pattern.</p>\n<pre><code>macro_rules! impl_example {\n    (\n        input_1 = $input_1:literal,\n        input_2 = ($($input_2:tt)*),\n        input_3 = {\n            grouped_input_1 = $grouped_input_1:literal,\n            grouped_input_2 = $grouped_input_2:ident,\n            grouped_input_3 = $grouped_input_3:expr,\n        },\n        input_4 = [$($input_4:expr),* $(,)?],\n    ) =&gt; { /*Expansion Here*/ };\n}\n\nimpl_example! {\n    input_1 = 123,\n    input_2 = (complex; grouped, input),\n    input_3 = {\n        grouped_input_1 = &quot;sample&quot;,\n        grouped_input_2 = Sample,\n        grouped_input_3 = concat!(&quot;...&quot;),\n        // ...\n    },\n    input_4 = [\n        array_value_1,\n        array_value_2,\n        array_value_3,\n        // ...\n    ],\n    // ... etc ...\n}</code></pre>\n<p>My reason for preferring this syntax is:</p>\n<ul><li>You cannot accidentally map a fragment to the wrong input without it being visible at the call site.</li><li>It uses a different binding syntax from struct initialization to distance itself from appearing to initialize an object.</li><li>Despite the binding syntax being different, it feels familiar enough to be immediately understood.</li></ul>\n<p>Though, I’ll admit the last two points aren’t that important. If you feel more comfortable you could use a more “struct field initialization” style format (<code>key: value</code>). That’s up to you!</p>\n<blockquote><p><strong>Don’t over-generalize these</strong>, accept them in <em>one</em> order - we’re only using these internally after all.</p>\n<p>I sometimes like to order them alphanumerically by key name, so that the order is at least consistent.</p></blockquote>\n<p><strong>Examples</strong></p>\n<p>An example of this in the wild are the integer types in the Rust language itself. Integer types (like <a href=\"https://doc.rust-lang.org/1.99.1/src/core/num/mod.rs.html#586-614\" rel=\"nofollow ugc noopener\"><code>u8</code></a>) use a crate-local <a href=\"https://doc.rust-lang.org/1.99.1/src/core/num/int_macros.rs.html\" rel=\"nofollow ugc noopener\"><code>int_impl</code></a> macro to implement common functions and traits.</p>\n<p>It’s also common to use declarative macros to assist in implementing a trait across tuples of different arities. Commonly useful in cases where your trait will just call the same trait on all tuple elements. You can see an example of this in the <a href=\"https://crates.io/crates/serde\" rel=\"nofollow ugc noopener\"><code>serde</code></a> crate with the crate-local <a href=\"https://docs.rs/serde/1.0.229/src/serde/core/ser/impls.rs.html#404-420\" rel=\"nofollow ugc noopener\"><code>tuple_impls!</code></a> macro.</p>\n<p>If you’d like a toy example - here’s one using some strongly typed time values. The macro helps us ensure the conversion implementations are consistent between the different types.</p>\n<pre><code>#[derive(Copy, Clone, Debug, PartialEq)]\npub struct OverflowError;\n\n#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\npub struct Hours(u32);\n\n#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\npub struct Minutes(u32);\n\n#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\npub struct Seconds(u32);\n\nmacro_rules! impl_time_functionality {\n    (\n        from = [$($from:ty),* $(,)?],\n        seconds_per = $seconds_per:expr,\n        try_from = [$($try_from:ty),* $(,)?],\n        type = $type:ty,\n    ) =&gt; {\n        // Ensure that we have common functions that we expect all of these time types to have.\n        //\n        // Reminder that you can open multiple impl blocks for a single type, so if there are\n        // functions that don&#39;t make sense to be commonly implemented here, then just write them\n        // in a separate impl block for the intended type outside of this macro.\n        impl $type {\n            // Helper constant to facilitate conversion impls.\n            // We don&#39;t want to export it publicly from this case.\n            pub(crate) const SECONDS_PER: u32 = $seconds_per;\n\n            pub fn to_u32(self) -&gt; u32 {\n                self.0\n            }\n        }\n\n        $(\n            impl TryFrom&lt;$try_from&gt; for $type {\n                type Error = OverflowError;\n                fn try_from(value: $try_from) -&gt; Result&lt;Self, Self::Error&gt; {\n                    // This const assert ensures we haven&#39;t used the helper macro improperly.\n                    const _: () = assert!(\n                        &lt;$try_from&gt;::SECONDS_PER &gt; $seconds_per,\n                        concat!(stringify!($try_from), &quot; must contain more seconds than &quot;, stringify!($type)),\n                    );\n                    Ok(Self(value.to_u32()\n                        .checked_mul(&lt;$try_from&gt;::SECONDS_PER / Self::SECONDS_PER)\n                        .ok_or(OverflowError)?))\n                }\n            }\n        )*\n\n        $(\n            impl From&lt;$from&gt; for $type {\n                fn from(value: $from) -&gt; Self {\n                    // This const assert ensures we haven&#39;t used the helper macro improperly.\n                    const _: () = assert!(\n                        &lt;$from&gt;::SECONDS_PER &lt; $seconds_per,\n                        concat!(stringify!($from), &quot; must contain fewer seconds than &quot;, stringify!($type)),\n                    );\n                    Self(value.to_u32() / (Self::SECONDS_PER / &lt;$from&gt;::SECONDS_PER))\n                }\n            }\n        )*\n    };\n}\n\nimpl_time_functionality! {\n    from = [],\n    seconds_per = 1,\n    try_from = [ Minutes, Hours ],\n    type = Seconds,\n}\n\nimpl_time_functionality! {\n    from = [ Seconds ],\n    seconds_per = 60,\n    try_from = [ Hours ],\n    type = Minutes,\n}\n\nimpl_time_functionality! {\n    from = [ Seconds, Minutes ],\n    seconds_per = 60 * 60,\n    try_from = [],\n    type = Hours,\n}\n\n#[test]\nfn test() {\n    assert_eq!(Hours::from(Seconds(60 * 60)), Hours(1));\n    assert_eq!(Minutes::from(Seconds(60 * 60)), Minutes(60));\n    assert_eq!(Seconds::from(Seconds(60 * 60)), Seconds(60 * 60));\n    assert_eq!(Hours::from(Minutes(60)), Hours(1));\n    assert_eq!(Minutes::from(Minutes(60)), Minutes(60));\n    assert_eq!(Seconds::try_from(Minutes(60)), Ok(Seconds(60 * 60)));\n    assert_eq!(Hours::from(Hours(1)), Hours(1));\n    assert_eq!(Minutes::try_from(Hours(1)), Ok(Minutes(60)));\n    assert_eq!(Seconds::try_from(Hours(1)), Ok(Seconds(60 * 60)));\n}</code></pre>\n<blockquote><p>Sometimes the deduplication is not worth the obfuscation that it creates, but that’s a case-by-case thing. For simple types like this (and the integer types from the standard library), the benefit is clear, as it produces the obvious intended end result and ensures the APIs are all implemented uniformly.</p>\n<p>If you find yourself adding a lot of special-casing and splitting your macro into many separate macros, that might be a sign that you’ve attempted to use this pattern in a place where it’s not helpful.</p>\n<p>In those cases, it’s probably best to just write out all your traits and impls by-hand, even if it results in some duplication.</p></blockquote>\n<p><a href=\"#format-like-expressions\">###</a></p>\n<h3 id=\"format-like-expressions\"><code>format!</code>-Like Expressions</h3>\n<p>A really popular reason for declarative macros is to match the <a href=\"https://doc.rust-lang.org/stable/std/macro.format.html\" rel=\"nofollow ugc noopener\"><code>format!</code></a> syntax from the standard library.</p>\n<p>You don’t always need to provide such a macro, sometimes you can just take <code>impl Into&lt;String&gt;</code> and let the user format as they please. But it can make things more readable in cases where the user will <em>always</em> be formatting a string, or if you want formatting to be conditionally compiled-out when disabling <code>alloc</code> support.</p>\n<p><strong>Examples</strong></p>\n<p>To point at the standard library again, we can look at the <a href=\"https://doc.rust-lang.org/1.99.1/src/core/macros/mod.rs.html#884-891\" rel=\"nofollow ugc noopener\"><code>todo!</code></a> macro. It’s simple enough that it’s just implemented right there as a declarative macro instead of being a built-in like many other macros (similar to <a href=\"https://doc.rust-lang.org/1.99.1/src/core/macros/mod.rs.html#43-70\" rel=\"nofollow ugc noopener\"><code>assert_eq!</code></a>, <a href=\"https://doc.rust-lang.org/1.99.1/src/core/macros/mod.rs.html#431-439\" rel=\"nofollow ugc noopener\"><code>matches!</code></a>, and a few others).</p>\n<p>It’s a bit of a low-hanging fruit, but the <a href=\"https://crates.io/crates/log\" rel=\"nofollow ugc noopener\"><code>log</code></a> crate has some pretty obvious examples; <a href=\"https://docs.rs/log/0.4.34/src/log/macros.rs.html#252-273\" rel=\"nofollow ugc noopener\"><code>info!</code></a>, <a href=\"https://docs.rs/log/0.4.34/src/log/macros.rs.html#204-225\" rel=\"nofollow ugc noopener\"><code>warn!</code></a>, and <a href=\"https://docs.rs/log/0.4.34/src/log/macros.rs.html#165-186\" rel=\"nofollow ugc noopener\"><code>error!</code></a>. In general, anything with a <code>format!</code>-like operation benefits from a declarative macro.</p>\n<p><code>assert!</code>-like macros are another example of this kind of macro. You may not think too much about it, but it can be nice to provide added details about a failure for unit tests. The <code>assert!</code> macros all accept format arguments at the end, and you can too if you need some adapter <code>assert!</code> macro.</p>\n<pre><code>macro_rules! assert_in_range {\n    ($input:expr, $low:expr, $high:expr, $($msg:tt)*) =&gt; {{\n        let input = $input;\n        let low = $low;\n        let high = $high;\n        assert!(\n            input &gt;= $low,\n            &quot;{}: range check failed: {input} &gt;= {low}&quot;,\n            format_args!($($msg)*),\n        );\n        assert!(\n            input &lt;= $high,\n            &quot;{}: range check failed: {input} &lt;= {high}&quot;,\n            format_args!($($msg)*),\n        );\n    }};\n}\n\n#[test]\nfn example() {\n    let number = 5;\n    assert_in_range!(number, 50, 100, &quot;formatted example (input={})&quot;, number);\n}</code></pre>\n<p>The failure here looks like this:</p>\n<pre><code>thread &#39;example&#39; (50) panicked at src/lib.rs:22:5:\nformatted example (input=5): range check failed: 5 &gt;= 50\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace</code></pre>\n<p><a href=\"#used-for-initializing-complex-types\">###</a></p>\n<h3 id=\"used-for-initializing-complex-types\">Used for Initializing Complex Types</h3>\n<p>For many types, you can get away with either the struct initialization format, or using the builder pattern.</p>\n<pre><code>#[derive(Default)]\nstruct Example {\n    foo: u8,\n    bar: String,\n    baz: bool,\n}\n\n// Some initialization patterns:\nfn struct_initialization() {\n    let object = Example {\n        foo: 0,\n        bar: format!(&quot;example formatted string&quot;),\n        baz: false,\n    };\n}\n\nfn struct_initialization_partial() {\n    let object = Example {\n        bar: format!(&quot;example formatted string&quot;),\n        ..Example::default()\n    };\n}\n\nfn builder_pattern() {\n    // `ExampleBuilder` type not shown for brevity.\n    let object = ExampleBuilder::default()\n        .with_foo(123)\n        .with_bar(format!(&quot;example formatted string&quot;))\n        .finish();\n}</code></pre>\n<p>But sometimes we want a different syntax than this, for readability reasons.</p>\n<p>Often custom syntaxes are only beneficial if there’s some common, well-accepted, pre-existing format (e.g. an existing data markup language, like JSON). But occasionally a purely custom syntax can be helpful.</p>\n<p>Containers are a great example of custom initialization syntax that everyone should have some experience with.</p>\n<p>It’s true you can (and should) implement <a href=\"https://doc.rust-lang.org/stable/std/iter/trait.FromIterator.html\" rel=\"nofollow ugc noopener\"><code>FromIterator</code></a> to initialize from some sequence of elements. But this syntax can be awkward for explicit initialization that isn’t coming from some already constructed values. So for developer convenience we often create small helper macros to improve readability.</p>\n<p>Like with many things relating to macros, only add them when you’re sure they’re useful. Think about whether the pre-existing methods for initializing objects is good enough.</p>\n<p><strong>Examples</strong></p>\n<p>It should go without saying, but the <a href=\"https://doc.rust-lang.org/stable/std/macro.vec.html\" rel=\"nofollow ugc noopener\"><code>vec!</code></a> macro is a really popular example of this. And soon we will have yet another version of this, with the <a href=\"https://doc.rust-lang.org/stable/std/macro.hash_map.html\" rel=\"nofollow ugc noopener\"><code>hash_map!</code></a> macro.</p>\n<p>The best example of this I can think of for object initialization is the <a href=\"https://docs.rs/serde_json/latest/serde_json/macro.json.html\" rel=\"nofollow ugc noopener\"><code>json!</code></a> macro from the <code>serde_json</code> crate.</p>\n<p>This is actually a good example of using declarative macros to do something non-trivial. Specifically, note that they hide the implementation details of the macro by splitting it into multiple macros, <a href=\"https://docs.rs/serde_json/1.0.154/src/serde_json/macros.rs.html#54-59\" rel=\"nofollow ugc noopener\"><code>json!</code></a> is the main one you call, and it redirects to another exported macro which is hidden from documentation called <a href=\"https://docs.rs/serde_json/1.0.154/src/serde_json/macros.rs.html#68-281\" rel=\"nofollow ugc noopener\"><code>json_internal</code></a>.</p>\n<p>Though, I will admit, <code>json!</code> is one of those declarative macros I think is teetering on the edge of “should have been a procedural macro”. Though, it might be hard to safely change it over at this point.</p>\n<p><a href=\"#reducing-boilerplate\">###</a></p>\n<h3 id=\"reducing-boilerplate\">Reducing Boilerplate</h3>\n<p>Sometimes you find yourself writing many similar lines of code within a small set of functions.</p>\n<p>In most cases, it’s best to just change these into helper functions and let the compiler optimize things. But sometimes you’ll run into situations where you can’t do that.</p>\n<ul><li>You need to generate a distinct <em>type</em> per functional configuration (e.g. not just logic or impls).</li><li>You’re using it to provide the body of a function that the macro is implementing, and you can’t generalize this function body over any trait bounds.</li><li>When your macro influences the surrounding control flow (<code>break</code>, <code>continue</code>, <code>return</code>).</li><li>For optimization reasons (which you have surely bench tested).</li></ul>\n<p><strong>Be careful when altering control flow.</strong></p>\n<p>It can have some utility for really simple, localized helper macros. But I tend to consider it to be an anti-pattern to <em>export</em> such macros. However, used very sparingly, in unique cases to assist in implementing something, it can be helpful.</p>\n<p>Honestly, I even lean away from it for crate-local macros as well. Obfuscating the control flow negatively impacts readability in my experience.</p>\n<p><strong>Examples</strong></p>\n<p>One example where this pattern being used for optimization reasons is within the Rust standard library. The <code>str</code> type specializes based on string lengths for optimization reasons (<a href=\"https://doc.rust-lang.org/1.99.1/src/alloc/str.rs.html#81-109\" rel=\"nofollow ugc noopener\"><code>specialize_for_lengths</code></a>; used <a href=\"https://doc.rust-lang.org/1.99.1/src/alloc/str.rs.html#200\" rel=\"nofollow ugc noopener\">here</a>).</p>\n<p>The <a href=\"https://crates.io/crates/bytes\" rel=\"nofollow ugc noopener\"><code>bytes</code></a> crate actually uses some macros to reduce code duplication. See the crate-local <a href=\"https://docs.rs/bytes/1.12.1/src/bytes/buf/buf_impl.rs.html#72-85\" rel=\"nofollow ugc noopener\"><code>buf_get_impl</code></a> macro. This is a good example of the macro providing a common implementation for a set functions. The functions that are being implemented simply invoke the macro to expand this common implementation.</p>\n<p>An example of a crate-exported macro used to produce new types can be found in the <a href=\"https://crates.io/crates/bitflags\" rel=\"nofollow ugc noopener\"><code>bitflags</code></a> crate. In this case, it uses some custom syntax that looks kind of like regular Rust code, so it’s a good reference for how to use some different fragment specifiers (like <code>meta</code> or <code>vis</code>).</p>\n<p>Finally, probably one of the most popular control-flow-impacting macros, is anyhow’s <a href=\"https://docs.rs/anyhow/latest/anyhow/macro.bail.html\" rel=\"nofollow ugc noopener\"><code>bail!</code></a> macro. As mentioned, I’m not a fan of these kinds of macros (including this one). But I want to mention it anyway, since it fits within this set of example use-cases, and likely has some popularity. (Another potential example of this is the standard library’s <a href=\"https://doc.rust-lang.org/nightly/core/task/macro.ready.html\" rel=\"nofollow ugc noopener\"><code>ready!</code></a> macro for polling futures.)</p>\n<p>A really simple example of this is constructing a newtype that redirects to the underlying implementation. We may want to ensure that the types are actually distinct from one another, but we may not want to re-implement the functionality the type provides (<a href=\"https://docs.rs/typed-ident/0.0.3/src/typed_ident/core/fmt/macros/impl_displayable_type.rs.html\" rel=\"nofollow ugc noopener\"><code>impl_displayable_type</code></a> - example usage <a href=\"https://docs.rs/typed-ident/0.0.3/src/typed_ident/core/fmt/bounded/as_lower_camel.rs.html#15-54\" rel=\"nofollow ugc noopener\">here</a> - is an example of this from one of my own crates, <a href=\"https://crates.io/crates/typed-ident\" rel=\"nofollow ugc noopener\"><code>typed-ident</code></a>).</p>\n<pre><code>// A simplified form of `impl_displayable_type` to use as an example.\nmacro_rules! impl_displayable_type {\n    (\n        name=$name:ident,\n        over=$over:ident,\n        docs=$docs:expr,\n    ) =&gt; {\n        #[doc = $docs]\n        pub struct $name($over);\n\n        impl core::fmt::Display for $name {\n            #[inline]\n            fn fmt(&amp;self, f: &amp;mut core::fmt::Formatter&lt;&#39;_&gt;) -&gt; core::fmt::Result {\n                self.0.fmt(f)\n            }\n        }\n    };\n}\n\n// We have some displayable types that we don&#39;t want to conflate.\n\nimpl_displayable_type! {\n    name = ObjectId,\n    over = u64,\n    docs = &quot;Example documentation here&quot;,\n}\n\nimpl_displayable_type! {\n    name = GroupId,\n    over = u64,\n    docs = concat!(\n        &quot;`docs` is an expression so you can do things like this.\\n&quot;,\n        &quot;\\n&quot;,\n        &quot;Multi-line documentation, for better readability!&quot;,\n    ),\n}\n\n// So now, if we have an API like this...\nstruct Object;\nimpl Object {\n    pub fn object_id(&amp;self) -&gt; ObjectId {\n        todo!()\n    }\n    pub fn group_id(&amp;self) -&gt; GroupId {\n        todo!()\n    }\n}\n\n// ... You can&#39;t accidentally do something like this.\nfn example_bad_usage_that_no_longer_compiles(object: Object) {\n    let group_id: GroupId = object.object_id(); // Fails to compile!\n}</code></pre>\n<blockquote><p>It can be tempting to use declarative macros in places where a <code>#[derive(...)]</code> procedural macro would make more sense. Try to avoid creating such macros unless necessary.</p>\n<p>A common toy example for declarative macros is to create a function on enums so you can get static strings of the enum variant names. But this can be accomplished through a derive macro, and that feels more idiomatic to me (like <a href=\"https://docs.rs/strum/latest/strum/derive.IntoStaticStr.html\" rel=\"nofollow ugc noopener\"><code>IntoStaticStr</code></a> from the <a href=\"https://crates.io/crates/strum\" rel=\"nofollow ugc noopener\"><code>strum</code></a> crate, or - maybe better - having a custom trait to represent this).</p>\n<p><strong>Do what you believe the end-user would find most natural.</strong> If what your macro is doing is implementing a trait - you probably ought to make it a derive macro unless you have good reason not to.</p>\n<p>We’ll talk more about derive macros when we cover procedural macros in a later article, though.</p></blockquote>\n<p><a href=\"#summary\">##</a></p>\n<h2 id=\"summary\">Summary</h2>\n<p><strong>Thanks for reading!</strong></p>\n<p>Macros are a really complex topic, so thanks for sticking with me through these articles as I try to explain them.</p>\n<p>If you were able to learn something new, and want to show your gratitude, please consider <a href=\"https://ko-fi.com/sigseis\" rel=\"nofollow ugc noopener\"><strong>sending a donation on Ko-Fi</strong></a>!</p>\n<p>I’d love to be able to work with the community full-time, and support like that will allow me to continue writing articles like these.</p>\n<p>In this article, we:</p>\n<ul><li>Learned about macro scoping, and how to export declarative macros.</li><li>Learned a method for organizing declarative macros for ease of maintenance.</li><li>Explored a small selection of use cases for declarative macros.</li><li>Saw some examples of declarative macro usage (some real-world, and other toy examples).</li></ul>\n<p>I still have a little more to say about declarative macros…</p>\n<p>The original draft of this article was 7500 words, and that’s too long. The next article will focus on best practices, and common pain points with declarative macros. Please look forward to it!</p>\n<p>I promise we’ll get to procedural macros eventually. :)</p>","headings":[{"level":1,"text":"Rust Declarative Macros: Organization, Scoping, and Common Use-Cases","id":"rust-declarative-macros-organization-scoping-and-common-use-case"},{"level":2,"text":"Table of Contents","id":"table-of-contents"},{"level":2,"text":"How To Integrate Declarative Macros Into Your Crate","id":"how-to-integrate-declarative-macros-into-your-crate"},{"level":3,"text":"Scoping Rules for Declarative Macros","id":"scoping-rules-for-declarative-macros"},{"level":3,"text":"Exporting Declarative Macros","id":"exporting-declarative-macros"},{"level":3,"text":"A Reminder About Macro Hygiene","id":"a-reminder-about-macro-hygiene"},{"level":3,"text":"How to Organize Declarative Macros","id":"how-to-organize-declarative-macros"},{"level":2,"text":"Use Cases for Declarative Macros","id":"use-cases-for-declarative-macros"},{"level":3,"text":"Implementing Traits and Functions","id":"implementing-traits-and-functions"},{"level":3,"text":"format!-Like Expressions","id":"format-like-expressions"},{"level":3,"text":"Used for Initializing Complex Types","id":"used-for-initializing-complex-types"},{"level":3,"text":"Reducing Boilerplate","id":"reducing-boilerplate"},{"level":2,"text":"Summary","id":"summary"}]}}