hash

hash(x[, h::UInt])

Compute an integer hash code such that `isequal(x,y)` implies `hash(x)==hash(y)`. The optional second argument `h` is a hash code to be mixed with the result.

New types should implement the 2-argument form, typically by calling the 2-argument `hash` method recursively in order to mix hashes of the contents with each other (and with `h`). Typically, any type that implements `hash` should also implement its own `==` (hence `isequal`) to guarantee the property mentioned above.

Examples

1. Calculate the hash code for an integer:

``````julia> hash(42)
0x2a``````

This example calculates the hash code for the integer `42`.

2. Calculate the hash code for a string:

``````julia> hash("Hello, Julia!")
0x9d7d3f6e1b4e6e3d``````

It calculates the hash code for the string `"Hello, Julia!"`.

3. Mix a custom hash code with the result:

``````julia> hash(10, 20)
0x1a``````

In this example, the custom hash code `20` is mixed with the hash code of the integer `10`.

4. Implement a custom type with its own hash function:

``````julia> struct Person
name::String
age::Int
end

julia> Base.hash(p::Person, h::UInt) = hash(p.name, p.age, h)

julia> p = Person("Alice", 25)
julia> hash(p)
0x1f3d0a522f7f7e9d``````

Here, a custom type `Person` is defined with its own `hash` function. The `hash` function is implemented by mixing hashes of the `name` and `age` fields along with the optional `h` argument.

When implementing the `hash` function for custom types, it is important to ensure that the `==` (equality) operator is also implemented to guarantee that equal objects have equal hash codes.

User Contributed Notes

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: