Struct 具有可变成员的Julia结构的等式推导

Struct 具有可变成员的Julia结构的等式推导,struct,julia,immutability,equality,Struct,Julia,Immutability,Equality,在下面的Julia代码中,由于BigInt是一个可变的结构,因此对于T{BigInt},我们的等式不起作用=是由BigInt自己明确定义的 julia> struct T{X} x :: X end julia> T{Int64}(1) == T{Int64}(1), T{Int64}(1) === T{Int64}(1) (true, true) julia> T{BigInt}(1) == T{BigInt}(1), T{BigInt

在下面的Julia代码中,由于
BigInt
是一个可变的结构,因此对于
T{BigInt}
,我们的等式不起作用<然而,代码>=是由
BigInt
自己明确定义的

julia> struct T{X}
           x :: X
       end

julia> T{Int64}(1) == T{Int64}(1), T{Int64}(1) === T{Int64}(1)
(true, true)

julia> T{BigInt}(1) == T{BigInt}(1), T{BigInt}(1) === T{BigInt}(1)
(false, false)

julia> T{BigInt}(1).x == T{BigInt}(1).x, T{BigInt}(1).x === T{BigInt}(1).x
(true, false)
有没有办法:

  • 为这些类型的结构自动生成一个
    ==
    ,这些结构只在每个字段上递归
    =
  • 或者将可变结构的不可变版本作为成员(如C++中的
    const
    ),而不是使用与
    BigInt
    等价的不可变版本
我的目标是避免在包含大量此类结构的包中使用样板文件。

这应该可以:

function my_equals(a::S, b::S) where S
    for name in fieldnames(S)
        if getfield(a, name) != getfield(b, name)
            return false
        end
    end
    return true
end
我试图通过

import Base.==

function ==(a::S, b::S) where S
    for name in fieldnames(S)
        if getfield(a, name) != getfield(b, name)
            return false
        end
    end
    return true
end
这具有预期的行为,但(毫不奇怪)似乎破坏了一些东西(即,在重新定义
==
之后,您甚至不能调用
exit()

如果要使用
=
,则可以让所有自定义
结构继承自某个抽象类型,如下所示:

abstract type Z end

struct T{X} <: Z
    x::X
end

struct S{X} <: Z
    x::X
    y::X
end

import Base.==

function ==(a::V, b::V) where V <: Z
    for name in fieldnames(V)
        if getfield(a, name) != getfield(b, name)
            return false
        end
    end
    return true
end
这不会干扰现有的
==

julia> T{BigInt}(1) == T{BigInt}(1)
true

julia> S{BigInt}(2, 5) == S{BigInt}(2, 5)
true

julia> T{BigInt}(1) == T{BigInt}(2)
false

julia> S{BigInt}(2, 5) == S{BigInt}(2, 3)
false