Struct Parametric struct with type constrains in Union

Hi there!

I would like to use a struct of the following form:

struct thing{T<:Function}

When I create an instance like this:


it works well. But when I try the other one:


I get the error ERROR: UndefVarError: T not defined

Is there another way to constrain my struct member to be either a float or a function?
Even better would be to constrain it to a function from R to R, but thats a different problem.

Try something like:

struct thing{T <: Union{Function, Float64}}

Thanks for the fast answer!
The drawback seems to be that the resulting type changes, if I understand it correctly depending on what concrete type I use in each thing.

Is the following solution I found better?
(Taken from different topic )

struct thin{T}
    function thin{T}(p,someother_member) where {T}
        T <: Function || throw(ArgumentError("invalid type"))

I can call every type of p via thing{Function}(p0,some0) and it has the type


I just don’t know whether that is a performance advantage.

I’m curious about the context where this problem arises.

You want to dispatch on a specific function T that is sometimes stored in thin but not always.

Generically, when I see a Union{Float64,Function} I wonder whether there is a cleaner approach.

If you have different “classes” of thing that are meant to dispatch to different methods of a given function, perhaps a Trait would be the way to go?

The idea is that the struct contains a function. But sometimes the function is a certain type of function, for example linear.
Then I replace the function by its parameterization, so that later on, I have the information available and can use tailored methods for the “high-structure function”.

Now writing it down, I have the feeling that I should create a subtype of Function, so that the special kind of function is still a function…
Thank you for making me think about it!