Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import all macros, derives, and procedural macros in Rust 2018 without using extern crate?

Tags:

rust

rust-2018

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.

like image 465
Tim Diekmann Avatar asked Jun 23 '18 09:06

Tim Diekmann


People also ask

How do I export macros in Rust?

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!

What is derive macro Rust?

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 .

Can you use macros in Rust?

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.

What is Macro_use?

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.


2 Answers

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.

like image 130
ljedrz Avatar answered Oct 11 '22 03:10

ljedrz


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::*;
like image 33
hellow Avatar answered Oct 11 '22 01:10

hellow