Expand description
A macro to compare structs, field by field.
This crate provides the compare_structs!
macro, which is useful for writing
assert!
-style tests on structs. It provides more detailed output than a
standard assert_eq!
on two struct instances.
§Basic Usage
To compare specific fields between two structs, provide the struct expressions and the identifiers of the fields to compare.
use cmp::compare_structs;
let struct_a = A { a: 1, b: "hello" };
let struct_b = B { a: 1, b: "world" };
// This will pass, as we only compare the `a` field.
compare_structs!(struct_a, struct_b, a);
§serde
feature
This crate has an optional serde
feature that allows comparing all fields
of a struct without specifying them. To use it, enable the feature in your
Cargo.toml
:
[dependencies]
cmp = { version = "1.0.0", features = ["serde"] }
With the serde
feature enabled, you can call compare_structs!
with just
two arguments. The structs must derive serde::Serialize
.
use cmp::compare_structs;
use serde::Serialize;
#[derive(Serialize)]
struct MyStruct {
field1: i32,
field2: String,
}
let a = MyStruct { field1: 1, field2: "test".to_string() };
let b = MyStruct { field1: 1, field2: "test".to_string() };
// Compares all fields
compare_structs!(a, b);
If there are missing fields in one of the expressions when using the serde
feature, the macro will panic with a clear error message indicating which
field is missing from which struct.
Macros§
- compare_
structs - Macro which is mostly useful when writing
assert!
tests on structs.