# Constrain type to variable sized union

**URL:** <https://discourse.julialang.org/t/constrain-type-to-variable-sized-union/89206>\
**Category:** General Usage\
**Tags:** performance, type, parametric-types\
**Created:** [October 24, 2022, 7:18pm UTC](https://discourse.julialang.org/t/constrain-type-to-variable-sized-union/89206 "2022-10-24T19:18:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![HashBrown](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hashbrown/32/43601_2.png) [@HashBrown](https://discourse.julialang.org/u/HashBrown)\
**Post date:** [October 24, 2022, 7:18pm UTC](https://discourse.julialang.org/t/constrain-type-to-variable-sized-union/89206/1 "2022-10-24T19:18:29Z")

</div>

I want to constrain a type parameter to be a variable sized union whose elements are concrete types of another parametric type. For example:

```julia
struct Foo{T}
    ...
end

struct Bar{T <: Union{Vararg{Foo}}}
    a::T
end

```

This doesn’t work because `Vararg` isn’t a type. Also the reason I don’t just use `a::Foo` without a type parameter is because I want `T` to be a small `Union` of concrete types itself. This is so that the compiler can use union splitting to optimize rather than have a field with an arbitrary abstract type.

---

<div class="post-metadata">

**Author:** ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)\
**Post date:** [October 24, 2022, 8:29pm UTC](https://discourse.julialang.org/t/constrain-type-to-variable-sized-union/89206/2 "2022-10-24T20:29:19Z")

</div>

`Union`s don’t have a size per se (not one dispatchable in your code anyway, without manually distinguishing cases), so the safest way to do this is to explicitly state the types you want to `Union` in the `Union`.

Subsets of that `Union` should still be subtypes of the larger one regardless, though I have not checked explicitly.

Do you have a specific application of this in mind?

---

<div class="post-metadata">

**Author:** ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)\
**Post date:** [October 24, 2022, 9:07pm UTC](https://discourse.julialang.org/t/constrain-type-to-variable-sized-union/89206/3 "2022-10-24T21:07:39Z")

</div>

It looks like

```julia
struct Bar{T <: Foo}
    a::T
end

```

should do what you want, based on the behavior of

```julia
julia> Union{Complex{Int64},Complex{Float64}} <: Complex
true

```
