derive-with

Crates.ioderive-with
lib.rsderive-with
version0.5.0
sourcesrc
created_at2023-10-18 16:32:16.070477
updated_at2024-01-20 15:47:48.528659
description`#[derive(With)]` generates with-constructor for each field in struct.
homepage
repositoryhttps://github.com/systemxlabs/derive-with
max_upload_size
id1006947
size12,053
张林伟 (lewiszlw)

documentation

README

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

Commit count: 12

cargo fmt