Summary

When a constant appears as a pattern, this is syntactic sugar for writing a pattern that corresponds to the constant’s value by hand. This operation is only allowed when (a) the type of the constant implements PartialEq, and (b) the value of the constant being matched on has “structural equality”, which means that PartialEq behaves the same way as that desugared pattern.

This RFC does not allow any new code, compared to what already builds on stable today. Its purpose is to explain the rules for constants in patterns in one coherent document, and to justify why we will start rejecting some code that currently works (see the breaking changes below).

Motivation

The main motivation to write this RFC is to finish what started in RFC 1445: define what happens when a constant is used as a pattern. That RFC is incomplete in several ways:

RFC 1445 had the goal of leaving it open whether we want constants in patterns to be treated like sugar for primitive patterns or for PartialEq-based equality tests. This new RFC takes the stance it does the former based on the following main design goals:

Guide-level explanation

Constants can be used as patterns, but only if their type implements PartialEq. Moreover, this implementation must be the automatically derived one, and that also applies recursively for the types of their fields:

#[derive(PartialEq)] // code fails to build if we remove this or replace it by a manual impl
enum E { Var1, Var2 }

const BEST_VAR: E = E::VAR1;

fn is_best(e: E) -> bool { matches!(e, BEST_VAR) }
#[derive(PartialEq)]
struct S { f1: i32, f2: E }

const MY_S: S = S { f1: 42, f2: BEST_VAR };

// Removing *either* `derive` or implementing `PartialEq` manually would lead to rejecting this code
fn is_mine(s: S) -> bool { matches!(s, MY_S) }

We say that a type that derives PartialEq has “structural equality”: the equality of this type is defined fully by the equality on its fields.

For matching on values of enum type, it is sufficient if the actually chosen variant has structural equality; other variants do not matter:

struct NonStructuralEq(i32);

impl PartialEq for NonStructuralEq {
    fn eq(&self) -> bool { true }
}

#[derive(PartialEq)]
enum MyEnum { GoodVariant(i32), NonStructuralVariant(NonStructuralEq) }

// This constant *can* be used in a pattern.
const C: MyEnum = MyEnum::GoodVariant(0);

This means the eligibility of a constant for a pattern depends on its value, not just on its type. That is already the case on stable Rust for many years and relied upon by widely-used crates such as http.

Overall we say that the value of the constant must have recursive structural equality, which is the case when all the types that actually appear recursively in the value (ignoring “other” enum variants) have structural equality.

Most of the values of primitive Rust types have structural equality (integers, bool, char, references), but two families of types need special consideration:

Reference-level explanation

When a constant C of type T is used as a pattern, we first check that T: PartialEq. Furthermore we require that the value of C has (recursive) structural equality, which is defined recursively as follows:

In particular, the value of C must be known at pattern-building time (which is pre-monomorphization).

After ensuring all conditions are met, the constant value is translated into a pattern, and now behaves exactly as-if that pattern had been written directly. In particular, it fully participates in exhaustiveness checking. (For raw pointers, constants are the only way to write such patterns. Only _ is ever considered exhaustive for these types.)

Practically speaking, to determine whether a struct/enum type’s PartialEq behaves exactly like the one generated by derive(PartialEq), we use a trait:

/// When implemented on a `struct` or `enum`, this trait indicates that
/// the `PartialEq` impl of `Self` behaves exactly like the one
/// generated by `derive(PartialEq)`:
/// - on a `struct`, it returns `true` if and only if comparing all
///   fields with their respective `PartialEq` returns `true`.
/// - in an `enum`, it returns `true` if and only if both values
///   have the same variant, and furthermore comparing the fields of
///   that variant with their respective `PartialEq` returns `true`
///   for all fields.
///
/// This trait should not be implemented on `union` types.
///
/// This is a "shallow" property in the sense that it says nothing about
/// the behavior of `PartialEq` on the fields of this type, it only relates
/// `PartialEq` on this type to that of its fields.
///
/// This trait is used when determining whether a constant may be used as a pattern:
/// all types appearing in the value of the constant must implement this trait.
///
/// All that said, this is a safe trait, so violating these requirements
/// can only lead to logic bugs or accidentally exposing an equality test that your
/// library would otherwise not provide, not to unsoundness.
trait StructuralPartialEq: PartialEq {}

This trait is automatically implemented when writing derive(PartialEq). For this RFC to be implemented, the trait can remain unstable can hence cannot be implemented directly by users. In the future, it might be possible for libraries that implement PartialEq by hand (for instance for performance reasons) to also implement StructuralPartialEq by hand, if they can promise that the comparison behaves as documented. (See “Future possibilities” for some of the open questions around that option.) The trait has PartialEq as a supertrait because its entire contract only makes sense for types that implement PartialEq.

Range patterns are only allowed on integers, char, and floats; for floats, neither end must be a NaN.

The behavior of such a constant as a pattern is the same as the corresponding native pattern. On floats are raw pointers, pattern matching behaves like ==, which means in particular that the value -0.0 matches the pattern 0.0, and NaN values match no pattern (except for wildcards).

Breaking changes

This RFC breaks code that compiles today, but only code that already emits a future compatibility lint:

When the RFC gets accepted, the floating-point lint should be adjusted to only cover the cases we are really going to reject, and all of them should be shown in dependencies or directly turned into hard errors.

Compiler/library cleanup

There also exists the nontrivial_structural_match future compatibility lint; it is not needed for this RFC so it can be removed when the RFC gets accepted.

Similarly, the StructuralEq trait no longer serves a purpose and can be removed.

Drawbacks

Rationale and alternatives

The main design rationale has been explained in the “Motivation” section.

Some possible alternatives include:

Prior art

RFC 1445 defines basically the same checks as this RFC; this RFC merely spells them out more clearly for cases the old RFC did not explicitly over (nested user-defined types, raw pointers), and adjusts to decisions that have been made in the mean time (accepting floating-point patterns).

This RFC came out of discussions in a t-lang design meeting.

Unresolved questions

Future possibilities