Stream: helpdesk (published)

Topic: When assigning to a vector, return the whole vector?


view this post on Zulip mbaz (Nov 04 2022 at 00:45):

I want to see if I can make it so an assignment to a custom array type returns the entire array. Documentation for = says that "a[i] = v calls setindex!(a,v,i)". I tried this:

import Base.setindex!
struct A
    a::Vector{Int}
end
a = A(zeros(Int,10));
function setindex!(x::A, value, index)
    x.a[index] = value
    return x
end

but it doesn't work; it still returns only the assigned value.

julia> a[5] = 1
1

It seems that = is not simply parsed to setindex!. Is there a way to define what should be returned in an assignment like this?

view this post on Zulip jar (Nov 04 2022 at 00:52):

julia> Meta.@lower a[5] = 99
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1      Base.setindex!(a, 99, 5)
└──     return 99
))))

view this post on Zulip jar (Nov 04 2022 at 00:54):

so I doubt it

view this post on Zulip mbaz (Nov 04 2022 at 00:54):

Oh, I should have thought about seeing the lowered code. Thanks!

view this post on Zulip mbaz (Nov 04 2022 at 00:55):

I agree, seems doubtful.


Last updated: Oct 02 2023 at 04:34 UTC