Why does indexed assignment return the assigned value instead of the container?

Witness

x = ['a']
setindex!(x, 'b', 1)  # ['b']
x[1] = 'c'            # 'c'

This behaviour is documented:

The syntax a[i,j,...] = x is converted by the compiler to (setindex!(a, x, i, j, ...); x).

(The documentation seems silent on the return value of setindex!.)

I have two questions:

  • main question: Why does indexed assignment return the assigned value?
  • side question: Why does setindex! return the container instead?

It is convenient for multiple assignments, for example:

julia> x = [1, 2, 3]; y = [4, 5, 6];

julia> x[2] = y[2] = 42;

julia> x
3-element Vector{Int64}:
  1
 42
  3

julia> y
3-element Vector{Int64}:
  4
 42
  6

It is convention that !-functions return the mutated container. This is also convenient for nesting, example (although not with setindex! which is rarely used directly):

julia> x = [1, 2, 3];

julia> push!(empty!(x), 42); # empty! returns x

julia> x
1-element Vector{Int64}:
 42
4 Likes