I'm experimenting with Rust Edition 2018. In Rust 2015 you use
#[macro_use]
extern crate log;
for importing macros. In Rust 2018 extern crate
is probably unidiomatic. Is there a way, to import all macros from the crate without extern crate
? For simple macros, importing it in the modules is fine, but complicated macros depend on several other macros, which is unhandy.
macros can be exported from the current crate using #[macro_export] . Note that this ignores all visibility. Given the following definition for a library package macs : mod macros { #[macro_export] macro_rules!
Derive macros These macros can create new items given the token stream of a struct, enum, or union. They can also define derive macro helper attributes. Custom derive macros are defined by a public function with the proc_macro_derive attribute and a signature of (TokenStream) -> TokenStream .
The most widely used form of macros in Rust is the declarative macro. These are also sometimes referred to as “macros by example,” “ macro_rules! macros,” or just plain “macros.” At their core, declarative macros allow you to write something similar to a Rust match expression.
By default macros are scoped to their module, but #[macro_use] will let it escape to the parent context, including all submodules from there. See Macros By Example - The Rust Reference. Yandros July 17, 2021, 12:10pm #3.
I don't see any way of importing only all the macros, but if you are fine with importing all the essential objects a crate provides, you should usually get all the macros by writing:
use the_crate_with_macros::*;
or
use the_crate_with_macros::prelude::*; // if available
This also works in Rust 2015 starting in version 1.30.
As you already stated you can import a single macro via
use foo::mac1;
To import multiple macros at once you can either use nested imports
use foo::{mac1, mac2, mac3};
or rely on the crate author that they will let you import it via a single glob, e.g.
use foo::macros::*;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With