# Understanding type instability related to StructArrays

**URL:** <https://discourse.julialang.org/t/understanding-type-instability-related-to-structarrays/89413>\
**Category:** General Usage\
**Tags:** type-stability, structarrays\
**Created:** [October 28, 2022, 12:57am UTC](https://discourse.julialang.org/t/understanding-type-instability-related-to-structarrays/89413 "2022-10-28T00:57:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jsjie](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jsjie/32/22477_2.png) [@jsjie](https://discourse.julialang.org/u/jsjie)\
**Post date:** [October 28, 2022, 12:57am UTC](https://discourse.julialang.org/t/understanding-type-instability-related-to-structarrays/89413/1 "2022-10-28T00:57:05Z")

</div>

A minimun example in REPL:

```julia
julia> using StructArrays

julia> mutable struct Foo
           foo::Int
       end

julia> mutable struct Bar
           bar::StructArray{Foo}
       end

julia> bar = Bar(StructArray([Foo(1), Foo(2)]))
Bar(Foo[Foo(1), Foo(2)])

julia> function get_bar(bar::Bar)
           return bar.bar
       end
get_bar (generic function with 1 method)

julia> @code_warntype get_bar(bar)
MethodInstance for get_bar(::Bar)
  from get_bar(bar::Bar) in Main at REPL[5]:1
Arguments
  #self#::Core.Const(get_bar)
  bar::Bar
Body::StructArray{Foo}
1 ─ %1 = Base.getproperty(bar, :bar)::StructArray{Foo}
└── return %1

```

in `@code_warntype`, `StructArray{Foo}` will be shown in red. But why is it type unstable?

ps: I found that get components from an isolated struct array is type stable. So the problem might be the use of struct array as a field of another struct. I’ve tried to change both Foo and Bar to immutable, but with no luck.

---

<div class="post-metadata">

**Author:** ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)\
**Post date:** [October 28, 2022, 1:39am UTC](https://discourse.julialang.org/t/understanding-type-instability-related-to-structarrays/89413/2 "2022-10-28T01:39:41Z")

</div>

The problem is that `StructArray{Foo}` is an abstract type:

```julia
julia> isconcretetype(StructArray{Foo})
false

```

The actual type of a `StructArray` is complicated:

```julia
julia> typeof(StructArray([Foo(1), Foo(2)]))
StructVector{Foo, NamedTuple{(:foo,), Tuple{Vector{Int64}}}, Int64} (alias for StructArray{Foo, 1, NamedTuple{(:foo,), Tuple{Array{Int64, 1}}}, Int64})

```

So you’re better off using a type parameter:

```julia
mutable struct Bar{S <: StructArray{Foo}}
   bar::S
end

```
