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.

@fieldwise_init
struct Foo(Hashable):
var value: Int
fn __hash__[H: Hasher](self, mut hasher: H):
hasher.update(self.value)

var foo = Foo()
print(hash(foo))
@fieldwise_init
struct Foo(Hashable):
var value: Int
fn __hash__[H: Hasher](self, mut hasher: H):
hasher.update(self.value)

var foo = Foo()
print(hash(foo))

Implemented traits

AnyType, UnknownDestructibility

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.

Was this page helpful?