Parametric struct without specifying type parameters

Maybe it’s a bad pattern (opinions?), but I somewhat frequently find myself creating structs to hold many parameters, where each parameter might have a couple of types and as the struct is only used within my own code, I’m not worried about strictly specifying exactly what types are allowed. So something like

struct Foo{T1,T2,T3}
    x::T1
    y::T2
    z::T3
end

but with maybe 20-30 type parameters. Those structs can be painful to maintain, for example if I want to add a new parameter in the middle of the struct, and keep the same numbering convention, I’d have to re-number all the following type parameters.

I wrote a macro to implicitly add type parameters to any fields without an explicit type - is this a crazy thing to do? Are there any drawbacks/gotchas that I’m not seeing? It would let me write

@autotyped struct FooAuto
    x
    y
    z
end

where that would be equivalent to Foo.

The code is fairly simple: GitHub - johnomotani/AutoTypedStructs.jl: Simplify creation of Julia structs with many parametrically typed fields
It also supports explicit types or type parameters if desired, for example

@autotyped struct Bar{T <: Number}
    x::String
    y::T
    z
end

is equivalent to

struct Bar{T <: Number, T1}
    x::String
    y::T
    z::T1

If anyone else has any interest in using this, I’ll register the package…

Opinions on the macro/package name and suggestions for changing it are also welcome!

Have you seen ConcreteStructs.jl? Looks equivalent/similar.

2 Likes

You’re not alone. I do that every time the intended field type is too long to type.
If my choice is to have either

struct Foo
    x::SubArray{ComplexF64, 1, Vector{ComplexF64}, Tuple{Base.Slice{Base.OneTo{Int64}}}, true}
end

or

struct Foo{T}
    x::T
end

I choose the latter.