Initialize fields of user-defined `types` in arbitrary order

type

#1

I’d like to know if it is possible to initialize the fields of a user-defined type (or struct) in a deliberate order by using the field names so that the order of defined variables in the code does not matter. In other words, my question is about using keywords in an inner or outer constructor.

I have something like the following snippet in mind, where the order of initialization of fields is opposite to the order of their appearance in the code:

    # Julia ver. 0.4.7

    type MyType
        x1
        x2
    
        MyType(y) = new(x2 = y, x1 = 0)  # inner constructor
    end

    MyType(a, b) = new(x2 = a, x1 = b)  # outer constructor

#2

Check out the Parameters.jl package to do this.


#3

Base.@kwdef macro is available out of the box (at least on Julia 0.6):

julia> Base.@kwdef struct MyType
           x::Int
           y::String = "default"
       end
MyType

julia> MyType(x=10)
MyType(10, "default")

julia> MyType(x=10, y="junk")
MyType(10, "junk")

julia> MyType(y="junk", x=10)
MyType(10, "junk")


#4

isn’t that clunky to need a macro for such a simple task? :roll_eyes:


#5

Macros are a first-class, core language feature and are excellent and widely-used for implementing these types of annotations (@inline @simd etc.).


#6

That issue has come up for us, because we have some types where, for reasons of space, we put the fields in the best order for packing with as little padding as possible, or to match some C structure, which doesn’t match what seems natural as far as a constructor.


#7

are there any implications for performance in case one uses the above method with Base.@kwdef ?


#8

Cross posted: https://stackoverflow.com/questions/48060390/initialize-fields-of-user-defined-types-in-arbitrary-order


#9

that’s my own question.


#10

That’s the point. I am letting other people know that you asked the same question on other sites so that way we can make sure people who are looking to help you can see what’s already been answered instead of just a small snippet from this site. I am sure someone would have added a snippet on keyword arguments and splatting, but it’s already laid out at that other site and would thus be a waste of their time. This is the reason why it’s generally recommended (on all forums) to not cross-post. Please take this as a (very gentle) warning: it’s not something that should be done but it’s not really too bad.


#11

Too bad in comparison to what? I’m confused now.


#12

Typo. It’s not really too bad.