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.
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!
Post Details
- Posted
- 5 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/rust/commen...