Search code examples
hashjuliaobjectid

Why does adding mutable produce different hash values?


I have a simple struct like this with no custom == or hash() methods:

struct IntroductionMessage
    message::String
end

When I call hash() both return the same value:

say_hello_introduction = IntroductionMessage("Hello World")
say_hello_introduction_alternate = IntroductionMessage("Hello World")

hash(say_hello_introduction))
hash(say_hello_introduction_alternate))

# Output:
3650104434
3650104434

When I add the mutable keyword, so it's now mutable struct IntroductionMessage, the hash() values are different:

2957940122
238434212

The string itself never changed, so why does adding mutable produce a different result?


Solution

  • By default immutable structs are hashed by value while mutable structs are hashed by reference. This matches the default equality operations.