# Question about type stability and struct

**URL:** <https://discourse.julialang.org/t/question-about-type-stability-and-struct/96834>\
**Category:** Performance\
**Tags:** struct, type-stability\
**Created:** [March 30, 2023, 8:51am UTC](https://discourse.julialang.org/t/question-about-type-stability-and-struct/96834 "2023-03-30T08:51:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![fdekerme](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fdekerme/32/43574_2.png) [@fdekerme](https://discourse.julialang.org/u/fdekerme)\
**Post date:** [March 30, 2023, 8:51am UTC](https://discourse.julialang.org/t/question-about-type-stability-and-struct/96834/1 "2023-03-30T08:51:28Z")

</div>

Hello ! 😃  
How do you achieve type stability with handwritten structures?  
For example, in the following code example, what do I need to return in the second `return` for the function `test` to be type stable? It return `(true, s1)` if `a<b` and “just” false if not.

```julia
struct S1
    x::Float64
    y::Vector{Float64}
end

function test(a ,b, c)
    if a<b
        s1 = S1(a, [a,b,c])
        return(true, s1)
    end
        return(false, ???)

```

Could we define a “neutral element” of structure `S1`?  
Thank you for your insight! 😃

---

<div class="post-metadata">

**Author:** ![HanD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hand/32/213908_2.png) [@HanD](https://discourse.julialang.org/u/HanD)\
**Post date:** [March 30, 2023, 10:31am UTC](https://discourse.julialang.org/t/question-about-type-stability-and-struct/96834/2 "2023-03-30T10:31:51Z")

</div>

There is not much point in using a separate boolean indicator for success, you can use `Union{S1, Nothing}` as an optional type.

```julia
function test(a ,b, c)::Union{S1, Nothing}
    if a<b
        s1 = S1(a, [a,b,c])
        return s1
    end
    return nothing
end

```

As the documentation of `InteractiveUtils.code_warntype` writes:

> Not all non-leaf types are particularly problematic for performance, so the results need to be used judiciously. In particular, unions containing either missing or nothing are displayed in yellow, since these are often intentional.

Using such optional types is quite common, and Julia handles them quite well, I don’t think you need to worry about them particularly.

---

<div class="post-metadata">

**Author:** ![fdekerme](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fdekerme/32/43574_2.png) [@fdekerme](https://discourse.julialang.org/u/fdekerme)\
**Post date:** [March 30, 2023, 1:07pm UTC](https://discourse.julialang.org/t/question-about-type-stability-and-struct/96834/3 "2023-03-30T13:07:21Z")

</div>

Yes indeed, this is a good solution!  
Thank you!
