Skip to main content
Log in

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.

@value
struct Foo(Hashable):
fn __hash__(self) -> UInt:
return 4 # chosen by fair random dice roll

var foo = Foo()
print(hash(foo))
@value
struct Foo(Hashable):
fn __hash__(self) -> UInt:
return 4 # chosen by fair random dice roll

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

Implemented traits

AnyType

Methods

__hash__

__hash__(self: T) -> UInt

Return a 64-bit hash of the type's data.

Returns:

A 64-bit integer hash of this instance's data.

Was this page helpful?