I am working on a project that involves comparing mutable structs with identical field values in Julia. However, I am encountering unexpected results when using the == and === operators, as they return false for mutable structs with identical field values. According to the Julia documentation, the == operator falls back to === for structs.
Based on the documentation at Mathematics · The Julia Language, the == operator falls back to === for structs. However, in this case, both comparisons return false.
Could someone please provide guidance on how to compare mutable structs correctly with identical field values in Julia? I appreciate any help and expertise you can provide.
julia> ==(x::MutRange, y::MutRange) = all(getfield(x, field) == getfield(y, field) for field in fieldnames(MutRange))
== (generic function with 195 methods)
julia> MutRange(1,3) == MutRange(1,3)
true
This custom comparison operator ensures that mutable structs with identical field values are correctly compared. I appreciate your expertise and assistance in resolving this problem.
Alternatively, you can define a function like this:
import Base: ==
function ==(a::MutRange, b::MutRange)
return a.start == b.start && a.finish == b.finish
end
This function can be used to compare MutRange instances similarly to the custom comparison operator. The custom comparison operator is defined as an anonymous function within the import Base: == statement, which may be unfamiliar to new Julia users. The alternative function provides a more explicit way to define the comparison operator.