assert_has_field - a Rust macro for checking if a struct has a specific field
This macro is designed to be used in Rust code to assert that a struct has a specific field and, if necessary, that this field of specific type.
Usage
The macro offers three syntaxes for checking if a struct has a field
assert_has_field!(Struct, field);- checks if the struct has a field with the given name.assert_has_field!(Struct, field: Type);- checks if the struct has a field with the given name and type.assert_has_field!(Struct, field :~ Type);- checks if the struct has a field with the given name and type that can be coerced to the specified typeType.
Checking that a struct has a field
use assert_has_field;
assert_has_field!; // This will compile
Checking that a struct has a field of a specific type
use assert_has_field;
assert_has_field!; // This will compile
Checking that a struct has a field of a specific type (failure case for a totally different type)
use assert_has_field;
assert_has_field!; // This will fail to compile
Checking that a struct has a field of a specific type (failure case for a type that can be coerced to)
;
assert_has_field!; // This will fail to compile
Checking that a struct has a field of a type that can be coerced to another type
use assert_has_field;
;
assert_has_field!;
Checking that a struct has a field of a type that can be coerced to another type (failure case)
use assert_has_field;
assert_has_field!; // This will not compile
How it works
On the real use-cases of this macro
Let's say that you're writing a backend server and have a DTO, which is meant
to be used on the frontend. Assume that this DTO aggregates different kinds of
data that pertains to a candidate. You may be in a situation where candidate_id
is stored in one of the fields-structures. You can use [assert_has_field] to
document that expectation and future-proof the type in case the field-structure
that used to store candidate_id is removed entirely or modified in a way that
moves or removes the candidate_id.