Skip to main content

field

Macro field 

Source
macro_rules! field {
    ($($t:tt)*) => { ... };
}
Expand description

Matches a structure or enum with a given field which is matched by a given matcher.

This takes two arguments:

  • a specification of the field against which to match, and
  • an inner Matcher to apply to that field.

For example:

#[derive(Debug)]
struct IntField {
  int: i32
}
verify_that!(IntField{int: 32}, field!(&IntField.int, eq(32)))?;

Tuple structs are also supported via the index syntax:

#[derive(Debug)]
struct IntField(i32);
verify_that!(IntField(32), field!(&IntField.0, eq(32)))?;

Enums are also supported, in which case only the specified variant is matched:

#[derive(Debug)]
enum MyEnum {
    A(i32),
    B,
}
verify_that!(MyEnum::A(32), field!(&MyEnum::A.0, eq(32)))?; // Passes
verify_that!(MyEnum::B, field!(&MyEnum::A.0, eq(32)))?; // Fails: wrong enum variant

The structure or enum may also be referenced from a separate module:

mod a_module {
    #[derive(Debug)]
    pub struct AStruct(pub i32);
}
verify_that!(a_module::AStruct(32), field!(&a_module::AStruct.0, eq(32)))?;

If the inner matcher is eq(...), it can be omitted:

#[derive(Debug)]
struct IntField {
  int: i32
}
verify_that!(IntField{int: 32}, field!(&IntField.int, 32))?;

Nested structures are not supported, however:

#[derive(Debug)]
struct InnerStruct(i32);
#[derive(Debug)]
struct OuterStruct {
    inner: InnerStruct,
}
verify_that!(value, field!(OuterStruct.inner.0, eq(32)))?; // Does not compile

§Specification of the field pattern

The specification of the field follow the syntax: (ref)? (&)? $TYPE.$FIELD. The & allows to specify whether this matcher matches against an actual of type $TYPE ($TYPE`` must implement Copy) or a &$TYPE`.

For instance:

#[derive(Debug)]
pub struct AStruct{a_field: i32};
verify_that!(AStruct{a_field: 32}, field!(&AStruct.a_field, eq(32)))?;
#[derive(Debug, Clone, Copy)]
pub struct AStruct{a_field: i32};
verify_that!(AStruct{a_field: 32}, field!(AStruct.a_field, eq(32)))?;

The ref allows to bind the field value by reference, which is required if the field type does not implement Copy.

For instance:

#[derive(Debug)]
pub struct AStruct{a_field: i32};
verify_that!(AStruct{a_field: 32}, field!(&AStruct.a_field, eq(32)))?;

If field! is qualified by both & and ref, they can both be omitted.

#[derive(Debug)]
pub struct AStruct{a_field: String};
verify_that!(AStruct{a_field: "32".into()}, field!(&AStruct.a_field, ref eq("32")))?;
verify_that!(AStruct{a_field: "32".into()}, field!(AStruct.a_field, eq("32")))?;

See also the macro property for an analogous mechanism to extract a datum by invoking a method.