#definition #struct #string #convert #macro

macro definition_string

Rust macro to convert a struct definition to a String

2 releases

new 0.1.1 Jan 15, 2025
0.1.0 Jan 14, 2025

#417 in Procedural macros

Download history 154/week @ 2025-01-10

154 downloads per month

MIT/Apache

5KB

definition_string

Rust macro to convert a struct defintion into a string (including comments).

crates.io Docs

Installation & Usage

cargo add definition_string
use definition_string::definition_string;

#[definition_string]
MyStruct {
    Stuff: i32,
}

let new_string: String = MyStruct::definition_string();

assert_eq!(new_string, r#"#[definition_string]\nMyStruct {\n    Stuff: i32,\n}"#)

Limitations

#[definition_string] is currently only usable on structs and enums. It would be possible to adapt it to functions or methods or basically anywhere you could slap on an attribute macro but at the moment there's no need.

#[definition_string] will only capture code BELOW it. For example:

#[derive(Debug, PartialEq, Eq)]
#[definition_string]
MyStruct {
    Stuff: i32,
}

Will NOT capture the derive macros in the generated String.

#[definition_string] will not capture non-doc comments between the macros and the struct, but it will capture comments on the fields. For example:

#[derive(Debug, PartialEq, Eq)]
#[definition_string]
//This comment will NOT be captured.
MyStruct {
    //This comment will be.
    Stuff: i32,
}

Just as a quick note most of these limitations could be avoided with nightly features or more complicated code, but for my use case it's not too important and preferable to keep the code simple.

Use Cases

My main motivation for creating this macro was for generating structured content from large language models. I found it was necessary to pass in a lot of struct definitions and obviously wasn't going to copy paste like some kind of barbarian.

Dependencies

~285–730KB
~17K SLoC