Better way to get the corresponding constructor from composite-type instances?

This was discussed a little while ago in this thread: Is there a way to get a UnionAll base type from a concrete type?

One good way seems to be to use the package ConstructionBase.jl, and write

using ConstructionBase
m1 = myT1(1.0)
constructorof(typeof(m1)) # myT1

It’s not defined for instances, but you could define

builder(x::Type) = constructorof(x)
builder(x) = builder(typeof(x))
2 Likes