Skip to content

Equality, maps and sets

Values compare by value with == when every part can (integers, bool, Str, f64, structs, enums, Option, Vec, Box), as in Go; closures, dyn and maps cannot. There is nothing to derive: equality that could only mean one thing is not something to write by hand.

Eq and Hash are built-in traits: a type has Eq when it compares by value as above, and Hash when it can also be a key. They cannot be implemented by hand. Generic code asks for them as bounds like any trait: fn count<T: Hash>(items: &Vec<T>) -> Map<T, i64>, fn find<T: Eq>(...).

Map<K, V> and Set<T> take any such key except ones containing f64 (NaN is not equal to itself). Lookups (get, contains, remove, take) read the key, so it is passed by value without being moved, or by reference. insert moves. Entries keep insertion order until something is removed; remove moves the last entry into the gap. take removes and returns the value. keys(), values() and items() return clones.

Map { "ann": 31, "bob": 27 } and Set { 2, 3, 5 } build one from its entries, in order. A key written twice as the same constant (a number, string, bool or enum variant) is an error. The types come from the entries or, for an empty Map {} / Set {}, from the annotation. Entries move into the collection like insert.

A generic type can also have methods for one instantiation only: impl Untrusted<Str> { ... } adds methods that Untrusted<i64> does not have.