Files
rust/library/core/src
Stuart Cook 2c314f93d3 Rollup merge of #144330 - gewitternacht:document-clone-eq, r=Amanieu
document assumptions about `Clone` and `Eq` traits

Most standard library collections break if `Clone` has a non-standard implementation which violates `x.clone() == x`. [Here](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=b7fc6dfa8410cbb673eb8d38393d81de) the resulting broken behaviour of different collections is shown. I originally created an issue at https://github.com/rust-lang/hashbrown/issues/629, but the conclusion there was that `x.clone()` resulting in an object that compares equal to the original one is probably a very universal assumption. However, this assumption is (to my knowledge) not documented anywhere.

I propose to make this assumption explicit in the `Clone` trait documentation. The property that seems the most reasonable to me is the following: When implementing both `Clone` and `PartialEq`, then
```text
x == x -> x.clone() == x
```
is expected to hold. This way, when also implementing `Eq`, it automatically follows that `x.clone() == x` has to hold, which should be enough for the collections to not break. At the same time, the property also works for the "normal" elements of a type with `PartialEq`. For the wording, I tried to follow the [`Hash` and `Eq`](https://doc.rust-lang.org/std/hash/trait.Hash.html#hash-and-eq) documentation.

As I am fairly new to Rust, it might well be that this property cannot be generally expected – it seems reasonable to me, but any counter-examples or critique, both content- and wording-wise, would be very welcome. If the property turns out to be too general, I would suggest to at least document the assumption of `x.clone() == x` for the collections somehow.

An additional thought of mine:
If it is indeed generally expected that `x == x -> x.clone() == x`, then, for the sake of completeness, one could also define that `x != x -> y != y for y = x.clone()` should hold, i.e., that an object that did not compare equal to itself before cloning, should also not compare equal to itself afterwards.
2025-08-11 12:21:07 +10:00
..
2025-07-04 11:52:17 +00:00
2025-08-06 16:55:50 +01:00
2025-07-21 12:49:45 +03:00
2025-08-07 00:08:11 +01:00
2025-08-06 16:55:50 +01:00
2025-08-06 16:55:50 +01:00
2025-08-06 13:22:38 +01:00
2025-08-10 01:11:45 -04:00
2025-08-10 01:11:45 -04:00
2025-08-10 01:11:45 -04:00
2025-07-03 20:03:49 +00:00
2025-08-06 16:55:50 +01:00
2025-08-06 16:55:50 +01:00
2025-08-06 16:55:50 +01:00
2025-07-21 09:11:21 +00:00
2025-05-12 15:33:30 +02:00
2024-07-29 08:26:52 +10:00
2025-07-04 11:35:00 +00:00
2025-08-06 16:55:50 +01:00
2025-08-06 16:55:50 +01:00
2024-06-11 15:47:00 +02:00
2025-07-04 11:52:17 +00:00
2025-06-15 22:08:41 +02:00
2025-08-06 16:55:50 +01:00
2024-11-27 15:14:54 +00:00
2025-04-09 12:29:59 +01:00
2025-07-04 11:52:17 +00:00
2025-08-06 16:55:50 +01:00