3 ms·
In particular, most traits you've seen for Rust, such as PartialEq, or here Ord (a claim that our type is totally ordered) are safe traits, this means you don't
by tialaramex 3y ago
In particular, most traits you've seen for Rust, such as PartialEq, or here Ord (a claim that our type is totally ordered) are safe traits, this means you don't need to utter the unsafe keyword to implement these traits, and so even though Rust clearly documents the traits as having specific requirements in fact it promises it won't actually cause UB if you ignore them, and the users of that trait must behave accordingly.
My misfortunate crate https://crates.io/crates/misfortunate https://crates.io/crates/misfortunate is a library of types that just deliberately implement various traits "wrongly" in order that you can play with the consequences.
For example Clone promises to uh, clone things, but Rust can't know if this Doodad is really a "clone" of that Doodad, only that the result was really the correct type, so if your type only implements Default my Multiplicity type wrapper will cheerfully claim it can be cloned anyway, cloning the wrapper doesn't get you a "real" clone but only your Default - the types look correct but what's inside is not a "clone" in any reasonable sense.
Rust does have what it calls unsafe traits, traits which you cannot implement without writing the "unsafe" keyword. They are solemn promises that you did what the documentation told you to, if you messed up in writing the unsafe trait then the resulting software may have Undefined Behaviour.
For example, my type wrapper Comte (named after the guy who invented the trick with a hat you've seen magicians do) claims to be an ExactSizeIterator. If it has one rabbit inside it, duh, exact size. Nope, it's a trick, we can just tap the Comte with our wand and produce an unlimited number of rabbits despite claiming to be an ExactSizeIterator, that's a bad idea but it's not Undefined Behaviour.
On the other hand Rust has the unsafe TrustedLen, which also says we can trust this iterator knows exactly how big it is, but because it's unsafe that's a solemn promise, if we took the Comte code but claimed to implement TrustedLen we're just despicable liars.