How to access the end index of an array as attribute of a class

struct Test
    data::Vector{Int}
end

Base.getindex(test::Test, index) = test.data[index]

Then, to get idex:

test = Test([1,2,3])

I can get:

test[1]
test[2]

How to get the last index value
test[end] didnot work.

Thank you for reading my question

1 Like

This could work:

 test[:][end]
1 Like

The error message seems clear enough to me, but maybe I’m just used to these things.

julia> test[end]
ERROR: MethodError: no method matching lastindex(::Test)
Closest candidates are:
  lastindex(::Markdown.MD) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.4/Markdown/src/parse/parse.jl:26
  lastindex(::Base64.Buffer) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.4/Base64/src/buffer.jl:19
  lastindex(::Cmd) at process.jl:639
  ...
Stacktrace:
 [1] top-level scope at REPL[9]:1

help?> lastindex
search: lastindex

  lastindex(collection) -> Integer
  lastindex(collection, d) -> Integer

  Return the last index of collection. If d is given, return the last index of collection along dimension d.

  The syntaxes A[end] and A[end, end] lower to A[lastindex(A)] and A[lastindex(A, 1), lastindex(A, 2)], respectively.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> lastindex([1,2,4])
  3
  
  julia> lastindex(rand(3,4,5), 2)
  4

julia> Base.lastindex(test::Test) = lastindex(test.data)

julia> test[end]
3
4 Likes

Awesome! Thank you very much for your reply

You can mark the previous post as the solution to help others with same question.

Yes, I did. Thank you!