Struct with immutable arrays

I need to be able to keep certain arrays of a mixed type (e.g. ImmutableN.n::Array{Int,1}) from being modified. Here is an example:

struct ImmutableN
  n::Array{Int64,1}
  cond::Float64
  ImmutableN(n) = new(n,rand(1)[1])
end

check = ImmutableN([1,2])
check.n[1] = 2 # works (bad)

I googled “julia immutable numeric array” and found this post, but I don’t understand what is going on here. Can someone please clarify this or suggest areas of the documentation that I should check?

1 Like

You are not mutating check (which is immutable). You are mutating something referred to by check.n.

For example, you will get an error if you try to assign check.n to a new array:

check.n = [3,4,5]    # gives an error: check is immutable

In the C programming language, the analogous thing would be int * const n = ...... You can’t change the pointer n (e.g. you can’t do n = n + 1), but you can change the data that n points to (you can do n[0] = 3).

For a read-only array in Julia, see e.g. GitHub - bkamins/ReadOnlyArrays.jl: A wrapper type around AbstractArray that is read-only (heap-allocated, for big arrays) or https://github.com/JuliaArrays/StaticArrays.jl (non-heap-allocated, faster for small arrays).

3 Likes

Thanks, this is helpful.