Skip to main content

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.

Note: The default reflection-based implementation iterates over all fields at compile time. For mutually recursive types (e.g., struct A has a field of type List[B] and struct B has a field of type A), this creates an infinite monomorphization cycle that causes the compiler to hang. To fix this, provide an explicit __hash__() implementation for at least one type in the cycle.

Implemented traits​

AnyType

Provided methods​

__hash__​

__hash__(self: _Self, mut hasher: T)

Accepts a hasher and contributes to the hash value by calling the update function of the hasher.

Args:

  • ​hasher (T): The hasher instance to contribute to.

Was this page helpful?