Derive Macro With

Source
#[derive(With)]
{
    // Attributes available to this derive:
    #[with]
}
Expand description

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

ยงGet started

1.Generate with-constructor for each field

use derive_with::With;

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

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

#[test]
fn test_struct() {
    let foo = Foo::default().with_a(1).with_b(1.to_string());
    assert_eq!(foo.a, 1);
    assert_eq!(foo.b, "1".to_string());

    let bar = Bar::default().with_0(1).with_1(1.to_string());
    assert_eq!(bar.0, 1);
    assert_eq!(bar.1, "1".to_string());
}

2.Generate with-constructor for specific fields

use derive_with::With;

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

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

#[test]
fn test_struct() {
    let foo = Foo::default().with_a(1);
    assert_eq!(foo.a, 1);

    let bar = Bar::default().with_1(1.to_string());
    assert_eq!(bar.1, "1".to_string());
}