Mojo trait
Hashable
A trait for types which specify a function to hash their data.
This hash function will be used for applications like hash maps, and don't need to be cryptographically secure. A good hash function will hash similar / common types to different values, and in particular the low order bits of the hash, which are used in smaller dictionaries, should be sensitive to any changes in the data structure. If your type's hash function doesn't meet this criteria it will get poor performance in common hash map implementations.
The Hashable trait has a default implementation of __hash__() that uses
reflection to hash all fields. This means simple structs can conform to
Hashable without implementing any methods:
@fieldwise_init
struct Point(Hashable):
var x: Int
var y: Int
var p = Point(1, 2)
print(hash(p))All fields must conform to Hashable. Override __hash__() for custom
hashing behavior.
Note: When implementing both Hashable and Equatable, ensure that
equal values produce equal hashes (i.e., if a == b then hash(a) == hash(b)).
The default implementations of both traits satisfy this property when all
fields implement both traits correctly.
Implemented traits
AnyType,
ImplicitlyDestructible
comptime members
__del__is_trivial
comptime __del__is_trivial
A flag (often compiler generated) to indicate whether the implementation of __del__ is trivial.
The implementation of __del__ is considered to be trivial if:
- The struct has a compiler-generated trivial destructor and all its fields
have a trivial
__del__method.
In practice, it means that the __del__ can be considered as no-op.
Provided methods
__hash__
__hash__[H: Hasher](self: _Self, mut hasher: H)
Accepts a hasher and contributes to the hash value by calling the update function of the hasher.
Parameters:
- H (
Hasher): Any Hasher type.
Args:
- hasher (
H): The hasher instance to contribute to.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!