Problem: setting up parametric struct

I am struggling to correctly set up a parametric struct.

This is most likely a very stupid question, however, I really don’t understand what is wrong with my code so please be gentle on me…

I want to create a struct which has a field that can be of various types which all are subtypes of one abstract type.

I created the following dummy example which is not working.

Can anyone explain to me

  1. How to fix this code and
  2. Why the enum version further below is working
abstract type Bar end 
struct SpecificBar <: Bar end 

mutable struct Foo{T <: Bar}

Foo([(1,1)], SpecificBar()) # returns error

I get the following error: ERROR: LoadError: MethodError: no method matching Foo(::Array{Tuple{Int64,Int64},1}, ::SpecificBar) Closest candidates are: Foo(::Array{Tuple,N} where N, ::T) where T<:Bar

My interpretation of the error message is that the issue is not with the field type but with the field x. If this is the case it is surprising to me that the below code using enum instead of abstract type works.

@enum BarEnum Bar1 Bar2

mutable struct Foo2

Foo2([(1,1)], Bar1)

Given I want to use multiple dispatch I feel it is better to use an abstract type instead of enums. Is this even a valid argument?

Thanks for your help!

You’ve run into this issue.. The issue is a missing default constructor for parametric types. Please comment on the issue so people can see this is something that actually bites people in the butt :slight_smile:

(btw, the solution is to do Foo{SpecificBar}([(1,1)], SpecificBar()))

1 Like

Great, thanks for your swift reply. I am happy to comment. No expert in programming and obviously Julia but I really didn’t get what the problem was.

So I guess the following is a quick fix for my code then.

Foo(x, type::Bar) = Foo{typeof{type}}(x, type)


1 Like


Foo(x, type::T) where T<:Bar = Foo{T}(x,type)

(the <:Bar is not needed for this to work, but with this construct you have an exact association with the struct definition).