我创建了一个结构
mutable struct mystruct
x::Float64
i::Int
end
现在当我使用函数 x_init 初始化它时:
function x_init(x::Number,i::Int)::mystruct
x = float(x)
Z = mystruct(x,i)
return Z
end
运行这个函数时我得到
julia> x_init(2,3)
mystruct(2.0, 3)
但是在测试中
@test x_init(2,3) == mystruct(2.0, 3)
我得到了false
。
我期望得到
true
。
有人可以解释一下为什么我得到
false
以及我应该如何为此类函数编写测试用例吗?
我可以测试一下
x_init(2,3).x == mystruct(2.0, 3).x && x_init(2,3).i == mystruct(2.0, 3).i
但是有没有更好的方法,不涉及检查每个变量?
==
(Base.:==
) 是您可以重载的通用相等运算符。如果您不超载 ==
,它将回落到您无法超载的 ===
(Core.:===
)。 ===
按值比较 immutable 对象,但它按内存地址比较 mutable 对象。尽管 x_init(2,3)
和 mystruct(2.0, 3)
具有相同的值,但它们是 mutable mystruct
的单独实例,因此具有不同的内存地址。
此重载将使
x_init(2,3) == mystruct(2.0, 3)
返回 true
:
Base.:(==)(a::mystruct, b::mystruct) = a.x===b.x && a.i===b.i
附注
::mystruct
方法标头中的 x_init
注释是不必要的。返回类型注释可能会在返回时添加 convert
步骤,但编译器可以推断 x_init
的返回类型必须是 mystruct
并且将省略 convert
步骤。