Zero() and iszero() for mutable structs

Hi there!
It is useful for me to store a mutable struct Line in a sparse matrix.
I had the impression that it is useful to define
Base.zero(::Line) = Line(0,1,0)
and
Base.zero(::Type{Line}) = Line(0,1,0)

unfortunately the following shows up in Julia:
iszero(zero(Line))

false
Also:
zero(Line)==zero(Line)

false

The same instead works as expected for usual static structs but I am not sure whether I can work with static structs.
I think I understand why this is (as for static structs there is one and only one zero struct, but for mutables, there may be copies that later on become actually different).
Still, is there another way to make this work?

iszero(x::Line) compares x == zero(::Line) with == defaults to ===, so really you need to define == to actually compare fields value

3 Likes

Oh, that makes sense, thank you!

Now that I think about it, would that be a good default behaviour for iszero for mutable structs?
I mean, when I have defined a zero for these, I guess I always want to know, whether a given instance currently behaves like a zero, whatever that might mean for the structure.
Then again I guess the use-case is so rare, nobody really cares.

In general, you should define zero for types that have a + operation, in which case zero should return the additive identity. If you aren’t doing arithmetic on your type (no +), then you probably shouldn’t define zero (regardless of whether your data is stored in a matrix).

2 Likes

I wanted to have it in order to access non-declared elements of the sparse matrix.
Is there some other fast way to check, whether a given index-pair of a sparse matrix is filled?

In Julia 1.6 there is a Base.isstored(A, i,j) function (added by #33821), though it is currently undocumented. The implementation is pretty trivial, though, and uses only the documented rowvals and nzrange functions if you want to copy it.

1 Like

Sounds reasonable, thanks for the hint, I will do that with Julia 1.6+.
But for now I’ll stick with the zero solution, if I actually need it, not sure yet.

For the record: My setting is a sparse graph, whose line-structs I store in a sparse matrix.