Constructor with Varargs

This works

using Pipe, Parameters

@with_kw struct X
    A
    B
end

x = (A=1, B=2 )
X( x... )

but this fails

x = (A=1, B=2, C=3 )
X( x... )

unless you manually filter x to only contain the fields of X.
or manually create a varargs constructor X(; A, B, varargs... ) = X( A, B)

Is there a way around this ?
Can the X struct automatically create a constructor with Varargs… functionality.
So that unused variables are dropped without causing an error

You could create your own macro to do this.

Here is what that macro looks like when expanded.

julia> @macroexpand @with_kw struct X
           A
           B
       end
quote
    begin
        $(Expr(:meta, :doc))
        struct X
            A
            B
            X(; A = error("Field '" * "A" * "' has no default, supply it with keyword."), B = error("Field '" * "B" * "' has no default, supply it with keyword.")) = begin
                    X(A, B)
                end
            X(A, B) = begin
                    new(A, B)
                end
        end
    end
...
end
2 Likes

Thanks Mark. looks good.

I was hoping there would be a way for it to happen automatically. But doesn’t seem to be the case