# Struct with immutable arrays

**URL:** <https://discourse.julialang.org/t/struct-with-immutable-arrays/36457>\
**Category:** New to Julia\
**Created:** [March 24, 2020, 6:18pm UTC](https://discourse.julialang.org/t/struct-with-immutable-arrays/36457 "2020-03-24T18:18:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mkarikom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkarikom/32/7096_2.png) [@mkarikom](https://discourse.julialang.org/u/mkarikom)\
**Post date:** [March 24, 2020, 6:18pm UTC](https://discourse.julialang.org/t/struct-with-immutable-arrays/36457/1 "2020-03-24T18:18:30Z")

</div>

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:

```julia
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](https://discourse.julialang.org/t/making-an-immutable-array-type/31129), 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?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [March 24, 2020, 6:25pm UTC](https://discourse.julialang.org/t/struct-with-immutable-arrays/36457/2 "2020-03-24T18:25:05Z")

</div>

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:

```julia
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](https://github.com/bkamins/ReadOnlyArrays.jl) (heap-allocated, for big arrays) or [https://github.com/JuliaArrays/StaticArrays.jl](https://github.com/JuliaArrays/StaticArrays.jl) (non-heap-allocated, faster for small arrays).

---

<div class="post-metadata">

**Author:** ![mkarikom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkarikom/32/7096_2.png) [@mkarikom](https://discourse.julialang.org/u/mkarikom)\
**Post date:** [March 24, 2020, 6:33pm UTC](https://discourse.julialang.org/t/struct-with-immutable-arrays/36457/3 "2020-03-24T18:33:19Z")

</div>

Thanks, this is helpful.
