Advanced Rust macros with derive-deftly

https://news.ycombinator.com/rss Hits: 4
Summary

[ docs: crate top-level | overall toc, macros | template etc. reference | guide/tutorial ] derive-deftly is a Rust package that you can use to define your own derive macros without having to write low-level procedural macros. The syntax is easy to learn, but powerful enough to implement macros of significant complexity. Just below is a simple example, to help you get a feel for the system. There is also comprehensive and rigorous reference material: Suppose you want to add accessor functions for the fields in your struct. You could do it by hand, like this: #![allow(unused)] fn main() { struct MyStruct { a: Vec<u8>, b: (u32, u32), c: Option<u16>, d: (u32, u32), // (more fields here ...) } impl MyStruct { fn get_a(&self) -> &Vec<u8> { &self.a } fn get_b(&self) -> &(u32, u32) { &self.b } fn get_c(&self) -> &Option<u16> { &self.c } fn get_d(&self) -> &(u32, u32) { &self.b } // (more accessors here...) } } But this is time consuming, and potentially error-prone. (Did you see the copy-paste error in get_d?) If you had to define a large number of accessors like this, or do it for a bunch of types, you might want an easier way. (Of course, in this case, you could use an existing crate. But let's suppose that there was no crate meeting your needs, and you had to build your own.) Here's how you could define and use a derive-deftly template to save some time and risk. #![allow(unused)] fn main() { use derive_deftly::{define_derive_deftly, Deftly}; // Defines the template define_derive_deftly! { Accessors: // Here, $ttype will expand to the toplevel type; in this case, // "MyStruct". impl $ttype { // This $( ... ) block will be repeated: in this case, once per field. $( // Here we define a "get_" function: In this definition, // $ftype is the type of the field, // $fname is the name of the field, // and $<...> denotes token pasting. fn $<get_ $fname>(&self) -> &$ftype { &self.$fname } ) } } // Applies the template to your struct #[derive(Deftly)] #[derive_deftly(Accessors)] st...

First seen: 2025-07-31 17:00

Last seen: 2025-07-31 20:01