I spent 10 hours building a macro so I’d never have to spend 10 minutes on boilerplate again.

88 points JodusMelodus 17 comments

I’m currently building an app that pulls a ton of data from an external API. If you use Rust, you know the drill: you get a UserDTO from the API, but you want a User in your domain. This usually leads to writing the same From trait implementation over and over again.
​I’m lazy, but I’m also curious. I’ve always been a bit intimidated by Rust’s procedural macros, so I decided to start a "sandbox" project called micro to learn how they work.

What’s in the sandbox so far?
I built a macro called FromDTO. Instead of manually mapping dozens of fields, I can just do this:

#[derive(FromDTO)]
#[from(api::TrackDTO)]
pub struct Track {
    pub id: i64,
    pub title: String,
    pub artist: Artist, // Automatically converts nested types!
}

It even handles those annoying Enum conversions and nested stuff like Option<Vec<T>> that usually makes you write a bunch of .map() and .collect() chains.

​The Goal:
This isn't meant to be some "production-ready framework" (at least not yet). It’s my playground for experimenting with Rust’s internals. I’m planning to keep adding more productivity-focused macros as I run into new "I'm too lazy to write this" problems.
​It’s been a blast seeing how the code actually gets transformed behind the scenes. If anyone else finds it useful or wants to see how the macro logic is structured, feel free to check it out!

https://crates.io/crates/micro