2 releases

0.1.1 Jan 1, 2025
0.1.0 Jun 6, 2024

#721 in Rust patterns

Download history 243/week @ 2024-12-26 115/week @ 2025-01-02 491/week @ 2025-01-09 845/week @ 2025-01-16 870/week @ 2025-01-23 788/week @ 2025-01-30 878/week @ 2025-02-06 721/week @ 2025-02-13 1075/week @ 2025-02-20 992/week @ 2025-02-27 833/week @ 2025-03-06 1182/week @ 2025-03-13 971/week @ 2025-03-20 1027/week @ 2025-03-27 893/week @ 2025-04-03 1172/week @ 2025-04-10

4,269 downloads per month

MIT license

7KB
99 lines

cmp

cmp is a Rust crate that provides a macro for comparing fields in structs, which is particularly useful when writing assert! tests.

Usage

cargo add cmp

compare_structs!

The compare_structs! macro compares specified fields of two structs. If the fields do not match, the macro will panic and output the fields that do not match.

Example

use cmp::compare_structs;

struct A<'a> {
    a: i32,
    b: &'a str,
    c: [(f64, f32); 2],
}

struct B<'a> {
    a: i32,
    b: &'a str,
    c: [(f64, f32); 2],
}

let struct_a = A {
    a: 10,
    b: "str",
    c: [(1.0, 1.0), (2.0, 2.0)],
};

let struct_b = B {
    a: 10,
    b: "diff str",
    c: [(1.0, 1.0), (2.0, 2.0)],
};

compare_structs!(struct_a, struct_b, a, c);

In this example, the compare_structs! macro compares the a and c fields of struct_a and struct_b. If they do not match, the macro will panic and output the fields that do not match.

Output

The output of the compare_structs! macro singles out the fields in the structs that do not match. For example:

thread 'tests::compare_different_structs' panicked at src/lib.rs:135:9:
c: [
    (
        1.0,
        1.0,
    ),
    (
        2.0,
        3.0,
    ),
] != [
    (
        1.0,
        1.0,
    ),
    (
        2.0,
        2.0,
    ),
]

note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

In this output, the c field of the two structs do not match, and the macro outputs the differing values.

No runtime deps