#struct #automatic #apply #derive #generate

macro struct_derive

automatically apply function on certain type of struct

2 releases

0.2.1 Jul 8, 2024
0.2.0 Jul 8, 2024

#650 in Procedural macros

Download history 218/week @ 2024-07-08 27/week @ 2024-07-29 11/week @ 2024-09-16 9/week @ 2024-09-23 37/week @ 2024-09-30 1/week @ 2024-10-07

58 downloads per month

MIT license

6KB
77 lines

struct_derive

StructUpdate is a derive macro in Rust that automatically generates an update_struct method for your struct. This method transforms all fields of type String in your struct to SCREAMING_SNAKE_CASE (all uppercase with underscores between words).

Usage

  1. First, you need to add the struct_derive dependency in your Cargo.toml file.
[dependencies]
struct_derive = "0.2.1"
  1. Then, you can use the #[derive(StructUpdate)] annotation on your struct. Also, you need to use the #[update_struct(with(ty = String, func = "to_screaming_snake_case"))] annotation to specify which type of fields need to be updated and what function to use to update these fields.
use struct_derive::StructUpdate;

fn to_screaming_snake_case(input: String) -> String {
    input.to_uppercase().replace(" ", "_")
}

#[derive(StructUpdate, Debug, Clone)]
#[update_struct(with(ty = String, func = "to_screaming_snake_case"))]
pub struct User {
    username: String,
    first_name: String,
    last_name: String,
    age: u32,
}
  1. Now, your struct has an update_struct method. You can call this method to update the fields in the struct.
fn main() {
    let mut user = User {
        username: "johndoe".to_string(),
        first_name: "John".to_string(),
        last_name: "Doe".to_string(),
        age: 30,
    };
    println!("{:#?}", user);

    user.update_struct();

    println!("{:#?}", user);
}

In the example above, the update_struct method transforms the username, first_name, and last_name fields to SCREAMING_SNAKE_CASE, but does not change the age field, as the age field is not of type String.

Dependencies

~0.6–1MB
~24K SLoC