You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 hash function uses an Int type for the default value of h, but Julia's Base.hash expects this argument to be a UInt (unsigned integer). This mismatch triggers the TypeError you'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

  1. 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 their first_num and second_num values match, which aligns with the proper semantic definition of equality.
  2. The hash Method: For hash-based collections like Set or Dict to 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 for h), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:55:08