Julia自定义类型Hash函数与相等性方法实现报错求助
Hey there, let's fix that error and get your custom equality logic working properly. Here's what's going wrong and how to fix it:
Root Causes of the Error
- Your
hashfunction uses anInttype for the default value ofh, but Julia'sBase.hashexpects this argument to be aUInt(unsigned integer). This mismatch triggers theTypeErroryou're seeing about a failed type assertion. - More importantly, using hash values to determine equality is a logical misstep. Hash collisions are rare but possible—two distinct objects could end up with the same hash. Equality should always be based on comparing the actual fields that define your struct's identity, not their hashes.
Corrected Code
mutable struct a first_num::Int second_num::Int end import Base.== import Base.hash # Define equality by directly comparing the struct's fields function ==(obj1::a, obj2::a) obj1.first_num == obj2.first_num && obj1.second_num == obj2.second_num end # Define hash with a UInt default value for the initial hash seed function hash(obj::a, h::UInt=UInt(33141651)) hash((obj.first_num, obj.second_num), h) end # Test the implementation a1 = a(2,3) a2 = a(2,3) println(a1 == a2) # This will now print true without errors
Why This Works
- The
==Method: This is the core of equality checking. We directly compare the two fields that make your struct unique—this ensures two instances are equal if and only if theirfirst_numandsecond_numvalues match, which aligns with the proper semantic definition of equality. - The
hashMethod: For hash-based collections likeSetorDictto work with your type, we need a hash function that guarantees equal objects have equal hashes. By combining the hashes of your struct's fields (and using a UInt default forh), we meet this requirement while eliminating the type error from your original code.
If you don't want to use a custom initial hash seed, you can also use zero(UInt) as the default for h—this is a standard default in Julia's Base hash implementations.
内容的提问来源于stack exchange,提问作者K. Steimel
相关产品推荐
相关产品推荐

