我創建了一個結構
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但是否有更好的方法不涉及檢查每個變數。
uj5u.com熱心網友回復:
==( Base.:==) 是可以多載的通用相等運算子。如果你不多載==,它會回退到===( Core.:===),你不能多載。按值===比較不可變物件,但按記憶體地址比較可變物件。盡管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
PS方法頭中的::mystruct注釋x_init是不必要的。回傳型別注釋可能會convert在回傳時添加一個步驟,但編譯器可以推斷出x_initmust的回傳型別,mystruct并將省略該convert步驟。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/385293.html
