#macro

no-std assign

Simple macro to allow mutating instance with declarative flavor

4 stable releases

1.1.1 Dec 30, 2020
1.1.0 Aug 8, 2020
1.0.1 Jun 30, 2020
1.0.0 Jun 25, 2020

#42 in No standard library

Download history 1221/week @ 2022-10-10 948/week @ 2022-10-17 1295/week @ 2022-10-24 1886/week @ 2022-10-31 1807/week @ 2022-11-07 1820/week @ 2022-11-14 1431/week @ 2022-11-21 1597/week @ 2022-11-28 1939/week @ 2022-12-05 1796/week @ 2022-12-12 1526/week @ 2022-12-19 1335/week @ 2022-12-26 1378/week @ 2023-01-02 1693/week @ 2023-01-09 1222/week @ 2023-01-16 1389/week @ 2023-01-23

5,852 downloads per month
Used in 36 crates (6 directly)

MIT license

8KB
89 lines

Build, Test

Assign

Mutate instances with declarative flavor!

This module provides macro assign! to allow mutating instance with declarative flavor

The motivation of this macro is to enable programmer to document a sequence of mutations instance fields as initialization by writing it in a declarative way. assign! macro also allows programmer to skip defining fields that has default value. Such case are used when a dependency is exposing an non-exhaustive struct

Usage

#[macro_use]
extern crate assign;

fn main() {
    struct SomeStruct {
        a: u32,
        b: Option<f32>,
        c: String,
    }
    impl SomeStruct {
        fn new() -> SomeStruct {
            SomeStruct {
                a: 1u32,
                b: None,
                c: String::from("old"),
            }
        }
    }

    // In order to treat the mutation of field `a` and `c` as an initialization,
    // Use assign to mutate field in declarative flavor, thus avoiding the risk inserting code
    // between the line that defines a field and the line that defines the other
    // Note that field `b` is skipped
    let instance = assign!(SomeStruct::new(), {
      a: 2u32,
      c: String::from("new"),
    });

    // Equivalent
    let instance2 = {
        let mut item = SomeStruct::new();
        item.a = 2u32;
        item.c = String::from("new");
        item
    };

    assert_eq!(instance.a, instance2.a);
    assert_eq!(&instance.c, &instance2.c);
    assert_eq!(instance.b, instance2.b);
}

License

MIT

No runtime deps