#generate #field #struct #derive #foo #i32 #with-constructor

macro derive-with

#[derive(With)] generates with-constructor for each field in struct

6 releases (breaking)

new 0.6.0 Feb 20, 2025
0.5.0 Jan 20, 2024
0.4.0 Jan 10, 2024
0.3.0 Oct 21, 2023
0.1.0 Oct 18, 2023

#2165 in Procedural macros

Download history 9/week @ 2024-10-30 8/week @ 2024-11-06 37/week @ 2024-11-13 74/week @ 2024-11-20 98/week @ 2024-11-27 27/week @ 2024-12-04 27/week @ 2024-12-11 11/week @ 2024-12-18 58/week @ 2024-12-25 13/week @ 2025-01-01 131/week @ 2025-01-08 157/week @ 2025-01-15 61/week @ 2025-01-22 63/week @ 2025-02-05 16/week @ 2025-02-12

146 downloads per month
Used in 6 crates (3 directly)

MIT license

9KB
108 lines

A custom derive implementation for #[derive(With)]

License Crates.io

Get started

1.Generate with-constructor for each field on named struct.

#[derive(With)]
pub struct Foo {
    pub a: i32,
    pub b: String,
}

This will generate code

impl Foo {
    pub fn with_a(mut self, a: impl Into<i32>) -> Self {
        self.a = a.into();
        self
    }
    pub fn with_b(mut self, b: impl Into<String>) -> Self {
        self.b = b.into();
        self
    }
}

2.Generate with-constructor for each field on tuple struct.

#[derive(With)]
pub struct Bar (i32, String);

This will generate code

impl Bar {
    pub fn with_0(mut self, field_0: impl Into<i32>) -> Self {
        self.0 = field_0.into();
        self
    }
    pub fn with_1(mut self, field_1: impl Into<String>) -> Self {
        self.1 = field_1.into();
        self
    }
}

3.Generate with-constructor for specific fields on named struct.

#[derive(With)]
#[with(a)]
pub struct Foo {
    pub a: i32,
    pub b: String,
}

This will generate code

impl Foo {
    pub fn with_a(mut self, a: impl Into<i32>) -> Self {
        self.a = a.into();
        self
    }
}

4.Generate with-constructor for specific fields on tuple struct.

#[derive(With)]
#[with(1)]
pub struct Bar (i32, String);

This will generate code

impl Bar {
    pub fn with_1(mut self, field_1: impl Into<String>) -> Self {
        self.1 = field_1.into();
        self
    }
}

References

Dependencies

~195–630KB
~15K SLoC