Question about type stability and struct

Hello ! :smiley:
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.

struct S1

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

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

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

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

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.


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

1 Like