Zero-dimensional array interface for custom type

I have

struct S
the_only_field
end

For my struct to hold data, I need it to have a field, and that means I need the field to have a name. But I would like to use it without having to define something like the_only_field(s::S) = s.the_only_field. So I figured I could make Julia think of S as a zero-dimensional array and have s[] give me s.the_only_field.

I’m trying to follow the documentaiton on the AbstractArray interface: Interfaces · The Julia Language

Is this the right way to do it?

Base.size(::S) = 0
Base.getindex(::S, i::Integer) = error("S is zero-dimensional. It has no indices. Use [] to get its contents.")
Base.getindex(s::S) = s.the_only_field
  1. The indexing seems about right, it resembles how Refs are implemented: getindex(b::RefValue) = b.x. I don’t think the erroring method for 1-dimensional indexing is necessary, but if you’re going that way you should also expand to multidimensional indexing.

  2. 0D arrays e.g. fill(1) should have a size of (), not 0. The default length as prod( () ) is 1.

  3. Subtype S{T}<:AbstractArray{T,0} if you really want to leverage AbstractArray methods.

2 Likes