# Make mutable struct read-only in local scope

**URL:** <https://discourse.julialang.org/t/make-mutable-struct-read-only-in-local-scope/122244>\
**Category:** General Usage\
**Created:** [November 4, 2024, 5:55pm UTC](https://discourse.julialang.org/t/make-mutable-struct-read-only-in-local-scope/122244 "2024-11-04T17:55:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [November 4, 2024, 5:55pm UTC](https://discourse.julialang.org/t/make-mutable-struct-read-only-in-local-scope/122244/1 "2024-11-04T17:55:11Z")

</div>

Is there a way to make a mutable-struct read-only in a given scope? (I don’t need that to be strictly impossible, just not user-friendly).

Something like having:

```julia
struct A
    x::Vector{Int}
end

```

and making it hard to use `setindex` on `x` of an instance of `A`. The use case is having a callback function in an algorithm, and in this callback function the user would have access to variables which he/she should be able to read, but not to modify.

(I guess this is mostly the case of all callback functions in optimization algorithms - and we just trust the users to not modify the data).

I imagined the possibility of creating a custom array type to wrap `x`, and thus expose

```julia
struct A
    x::ReadOnlyArray{Vector{Int}}
end

```

without defining `setindex` for `ReadOnlyArray`. (now that I wrote the name it feels that someone invented this already…). But implementing an array interface seems a bit too much.

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [November 4, 2024, 5:55pm UTC](https://discourse.julialang.org/t/make-mutable-struct-read-only-in-local-scope/122244/2 "2024-11-04T17:55:55Z")

</div>

> [@lmiq](#):
>
> (now that I wrote the name it feels that someone invented this already…)

Yeah, there it is: [GitHub - JuliaArrays/ReadOnlyArrays.jl: A wrapper type around AbstractArray that is read-only](https://github.com/JuliaArrays/ReadOnlyArrays.jl)
