Metaprogamming

Hi there,

I am writing a module with dozens of MyType like structure (as below), that all belong to an Abstract super type. I would like to be able to write a meta constructor (roughly sketched below). Is it possible?

struct MyType <: SomeAbstractType
    field1
    field2
    field3
    other::Dict
end

function MyType(d::Dict{AbstractString,AbstractString})
    var1 = f(d, "field1")
    var2 = f(d, "field2")
    var3 = f(d, "field3")

    MyType(var1, var2, var3, d)
end

function meta_constructor(d::Dict{AbstractString,AbstractString}, input::T)
     where T <: SomeAbstractType

    mytuple = for fields in fieldnames(T) ...

    T(mytuple)
end

Yes, that is possible. However, if you’re constructing from a dict, which will be type-unstable and not super performant, I don’t see a need to do it. I don’t think you gain anything from your current solution.

A lot of lines actually … roughly 1k … and I am a bit lazy

Does this not work:

function meta_constructor(d::Dict{AbstractString,AbstractString}, input::T)
     where T <: SomeAbstractType
    T((d[string(fld)] for fld in fieldnames(T))...)
end

?
(not sure what the f(d, "field1") is about, but this could be added too)

Thanks, I’m going to try it!

Corrected an error in the example. Probably you’re aware of this:
Also if you use a Dict{Symbol, AbstractString} then you can drop the string conversion. Last, if you can use a Dict{Symbol, String} and uses fields field1::String, you might speed things up.