Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

30
Let's talk macros: how to use them, when to use them, and why
Post Body

As was discussed in a good number of recent Rust 2019 posts, a large number of RFC proposals are about syntactic sugar, often to reduce boilerplate.

Thing is, when you see boilerplate, your tool to use should be a declarative macro, not an RFC to change the language itself.

So here, I wanted to share how I use declarative macros to reduce boiler plate in my code, and thereby demystify a fairly powerful tool available to Rust developers. This isn't a tutorial on macros, but a higher level discussion of how they can be used, and how they are used.

Let's say you have a new helper trait, and you want to implement it for a bunch of default Rust data types.

Here's the initial playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=fda8d4cfddc7a72b2b36385e305c9117

So as you can see, there's a helper trait, then a helper trait for the helper trait, so the helper trait is implemented based on the helper trait for the helper trait.

However, this helper trait for the helper trait is only implemented for u8.

If we want to implement it for other types, we'd need to copy the impl HelperHelperTrait for... part several times.

Or! We can write a macro.

A quick example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7671c6be846b9e66038e6659f37423b4

Said macro let us avoid copy and paste code repetitively, its still readable, maintainable, and clear.

And it took me about three minutes because of my practice and experience.

And this is how you reduce boilerplate using macros. Write a simple macro that iterates over input types or names, implements simple code or a trait for that type.

Now, if I needed to add some actual implementation code, I change it in one spot, rather than 12 spots.

DRY code was achieved as well.

Don't change the language; change your chosen tools!

Add your own examples of macro usage in the comments below!

Author
Account Strength
100%
Account Age
13 years
Verified Email
Yes
Verified Flair
No
Total Karma
20,627
Link Karma
4,816
Comment Karma
15,646
Profile updated: 4 days ago
Posts updated: 7 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
5 years ago