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
  ImmutableN(n) = new(n,rand(1)[1])

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?

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. (heap-allocated, for big arrays) or (non-heap-allocated, faster for small arrays).


Thanks, this is helpful.