AlQuemist
AlQuemist

Reputation: 1304

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

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

Upvotes: 1

Views: 156

Answers (2)

juliohm
juliohm

Reputation: 3779

As alternative answer, you can also make use of the Parameters.jl package:

using Parameters

@with_kw struct Foo
    x::Int = 1
    y::Float64 = 2.0
end

# now the following code works
Foo(x=3, y=4.)
Foo(y=5.)

There are no performance penalties. The Parameters.jl package basically does the same trick explained in Alexander Morley's answer with some extra features like default values for the fields.

Upvotes: 1

Alexander Morley
Alexander Morley

Reputation: 4181

You could do something like the below. This would work even nicer with NamedTuples coming in 0.7. (NB: this is just an idea you would probably want to add some checks/optimizations).

struct Foo
       x
       y
end

function Foo(;kwargs...)
           kwargnames = [x[1] for x in kwargs]
           Foo([kwargs[findfirst(kwargnames,i)][2] for i in fieldnames(Foo)]...)
ends

Foo(x=10,y=20) == Foo(y=20,x=10)

Upvotes: 3

Related Questions