Function get_substructure_equality_expr

Source
fn get_substructure_equality_expr(
    cx: &ExtCtxt<'_>,
    span: Span,
    substructure: &Substructure<'_>,
) -> P<Expr>
Expand description

Generates the equality expression for a struct or enum variant when deriving PartialEq.

This function generates an expression that checks if all fields of a struct or enum variant are equal.

  • Scalar fields are compared first for efficiency, followed by compound fields.
  • If there are no fields, returns true (fieldless types are always equal).

Whether a field is considered “scalar” is determined by comparing the symbol of its type to a set of known scalar type symbols (e.g., i32, u8, etc). This check is based on the type’s symbol.

§Example 1

#[derive(PartialEq)]
struct i32;

// Here, `field_2` is of type `i32`, but since it's a user-defined type (not
// the primitive), it will not be treated as scalar. The function will still
// check equality of `field_2` first because the symbol matches `i32`.
#[derive(PartialEq)]
struct Struct {
    field_1: &'static str,
    field_2: i32,
}

§Example 2

mod ty {
    pub type i32 = i32;
}

// Here, `field_2` is of type `ty::i32`, which is a type alias for `i32`.
// However, the function will not reorder the fields because the symbol for
// `ty::i32` does not match the symbol for the primitive `i32`
// ("ty::i32" != "i32").
#[derive(PartialEq)]
struct Struct {
    field_1: &'static str,
    field_2: ty::i32,
}

For enums, the discriminant is compared first, then the rest of the fields.

§Panics

If called on static or all-fieldless enums/structs, which should not occur during derive expansion.