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

macro derive-with

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

6 releases (breaking)

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

#1726 in Procedural macros

Download history 58/week @ 2024-11-19 102/week @ 2024-11-26 33/week @ 2024-12-03 37/week @ 2024-12-10 12/week @ 2024-12-17 58/week @ 2024-12-24 12/week @ 2024-12-31 127/week @ 2025-01-07 156/week @ 2025-01-14 64/week @ 2025-01-21 3/week @ 2025-01-28 62/week @ 2025-02-04 20/week @ 2025-02-11 165/week @ 2025-02-18 103/week @ 2025-02-25 97/week @ 2025-03-04

390 downloads per month
Used in 8 crates (5 directly)

MIT license

20KB
284 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

#[automatically_derived]
impl Foo {
    pub fn with_a(self, a: impl Into<i32>) -> Self {
        Self {
            a: a.into(),
            ..self
        }
    }
    pub fn with_b(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

#[automatically_derived]
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

#[automatically_derived]
impl Foo {
    pub fn with_a(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

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

More examples can be found in tests

References

Dependencies

~200–630KB
~15K SLoC