Description
This is the summary issue for the illegal_struct_or_enum_constant_pattern
future-compatibility warning and other related errors. The goal of
this page is describe why this change was made and how you can fix
code that is affected by it. It also provides a place to ask questions
or register a complaint if you feel the change should not be made. For
more information on the policy around future-compatibility warnings,
see our breaking change policy guidelines.
What is the warning for?
Rust 1.0 accepted a number of patterns -- and in particular accepted constant in patterns --
in a broader range of situations that was originally intended. RFC 1445 spelled out
some restrictions on what kinds of constants can be used in patterns, at least until the
final semantics are affirmatively decided. The intention is that user-defined struct
and
enum
types can only be used in match patterns if they derive the PartialEq
and Eq
traits (note that the traits must be automatically derived using #[derive(...)]
, they cannot
be implemented by hand).
This means that a match like this is illegal:
struct Foo { x: u32 }
const BAR: Foo = Foo { x: 0 };
let foo = Foo { x: 0 };
match foo {
BAR => ...,
_ => ...
}
To make it legal, add #[derive(PartialEq, Eq)]
to the Foo
struct.
The reason for this restriction is that pattern matching does not
actually invoke the Eq
methods defined in those traits.
Instead, internally, it compares each field deeply and recursively.
If you are using #[derive]
, this is guaranteed to be equivalent
to invoking the methods by hand. But if you are not using #[derive]
,
then the Eq
comparison method could do arbitrary things.
When will this warning become a hard error?
At the beginning of each 6-week release cycle, the Rust compiler team
will review the set of outstanding future compatibility warnings and
nominate some of them for Final Comment Period. Toward the end of
the cycle, we will review any comments and make a final determination
whether to convert the warning into a hard error or remove it
entirely.
Current status
- Restrict constants in patterns #32199 introduces the
illegal_struct_or_enum_constant_pattern
lint as warn-by-default - Make sufficiently old or low-impact compatibility lints deny-by-default #36894 makes the
illegal_struct_or_enum_constant_pattern
lint deny-by-default - Turn sufficiently old compatibility lints into hard errors #42136 makes the
illegal_struct_or_enum_constant_pattern
lint a hard error
Activity