How do I implement array indexing?

I have this array type:

struct Delay{T}
	head_idx::Int
	arr::Vector{T}
	function Delay{T}(length::Int) where T
		if ispow2(length)
			arr = zeros(T,length)
			new(0, arr)
		else
			throw(ArgumentError("Length is not power of 2"))
		end
	end
end

and I implemented the getindex function

function getindex(A::Delay{T},idx) where T
	if idx > 0
		throw(ArgumentError("Only accepts negative indexes"))
	else
		return 1
	end
end

then I define test as

test = Delay{Float32}(8)

When I try to use test[1] it errors with ERROR: MethodError: no method matching getindex(::Delay{Float32}, ::Int64) but if I use getindex function directly it works

julia> getindex(test,-1)
1

What happened?

You need to explicitly import the Base.getindex function:


julia> function Base.getindex(A::Delay{T},idx) where T
               if idx > 0
                       throw(ArgumentError("Only accepts negative indexes"))
               else
                       return 1
               end
       end

julia> test[-1]
1


Equivalent to:

import Base.getindex
function getindex(...) ...

It works! Thanks

Generalizing, what functions should I implement for my array type? In Python, there is this: 3. Data model — Python 3.10.6 documentation which states which methods that I should implement so that my class acts like a list, is there a documentation like this for Julia?

The page to read is this one, I think: Interfaces · The Julia Language

Depending on what you need to do with your data you might need only the indexing part, or something else.

If you do want it to be an array type, look at the AbstractArray section.