about summary refs log tree commit diff
path: root/compiler/rustc_errors/src
diff options
context:
space:
mode:
authorStuart Cook <Zalathar@users.noreply.github.com>2025-08-11 12:21:07 +1000
committerGitHub <noreply@github.com>2025-08-11 12:21:07 +1000
commit2c314f93d3303f9cd756adb29aae929785e886ac (patch)
treea260b730eb9f56e1550fb51af3511d4bca6e3f02 /compiler/rustc_errors/src
parentd06b3b432fbbed08182bee526f43e64276c3037d (diff)
parentfadc961d99f221fd720f97dc9eec61c2332cd451 (diff)
downloadrust-2c314f93d3303f9cd756adb29aae929785e886ac.tar.gz
rust-2c314f93d3303f9cd756adb29aae929785e886ac.zip
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.
Diffstat (limited to 'compiler/rustc_errors/src')
0 files changed, 0 insertions, 0 deletions