macro reusable

Composable struct fields - reuse struct fields in other structs

1 unstable release

0.1.0 Jan 14, 2023
Download history 227/week @ 2024-07-12 209/week @ 2024-07-19 260/week @ 2024-07-26 110/week @ 2024-08-02 330/week @ 2024-08-09 302/week @ 2024-08-16 247/week @ 2024-08-23 163/week @ 2024-08-30 231/week @ 2024-09-06 193/week @ 2024-09-13 275/week @ 2024-09-20 232/week @ 2024-09-27 199/week @ 2024-10-04 197/week @ 2024-10-11 218/week @ 2024-10-18 225/week @ 2024-10-25

895 downloads per month

MIT/Apache

7KB

Reuse - composable struct fields

An example of re-using struct fields across multiple structs in code by storing the source of structs across macros.

Usage

  1. Add this macro to your project

  2. Add a #[reusable(name)] attribute to the structs you want to able to copy, where the name is a globally unique identifier for the struct (best to namespace using your crate and module names)

  3. Add a #[reuse(name)] attribute to the structs you want to reuse using the same name used in the attribute above

Example

use reusable::{reusable, reuse};

#[reusable(test_name)]
#[derive(Debug)]
struct Name {
    firstname: String,
    surname: String,
}

#[reuse(test_name)]
#[derive(Debug)]
struct Fullname {
    middlename: String,
}

fn main() {
    let example = Fullname {
        firstname: "Bob".to_string(),
        middlename: "Frank".to_string(),
        surname: "Junior".to_string(),
    };
    dbg!(example);
}

How it works

  1. This crate relies heavily on macro_state to share data between macro calls.

  2. The reusable attribute copies the tokenstream of a struct to a global state using the provided name as a key

  3. The reuse attribute reads the tokenstream set by reusable, parses the structs matching the names given and then appends the fields to the generated struct (any fields with the same name are skipped so can be overriden)

Note: multiple names can be provided to the reuse attribute, e.g. #[reuse(name1, name2)].

Works in stable Rust, no nightly required.

Alternatives

Other crates can provide similar functionality such as:

born - generates macros from inlined struct definitions that generate new structs

Dependencies

~1.5MB
~37K SLoC