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
-
Calculate the hash code for an integer:
julia> hash(42) 0x2aThis example calculates the hash code for the integer
42. -
Calculate the hash code for a string:
julia> hash("Hello, Julia!") 0x9d7d3f6e1b4e6e3dIt calculates the hash code for the string
"Hello, Julia!". -
Mix a custom hash code with the result:
julia> hash(10, 20) 0x1aIn this example, the custom hash code
20is mixed with the hash code of the integer10. -
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) 0x1f3d0a522f7f7e9dHere, a custom type
Personis defined with its ownhashfunction. Thehashfunction is implemented by mixing hashes of thenameandagefields along with the optionalhargument.
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.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.