Create a struct with uninitialized fields


Having a mutable struct, e.g.:

mutable struct Point

is it possible to construct its instance with uninitialized fields and set them later? E.g.:

p = create_uninitialized(Point)    # <-- anything like this?
p.x = 10.0
p.y =  20.0

Note: we can do it with arrays, e.g. Array{Float64,1}(10).

Alternatively, I’d be happy to hear about similar() for structs, i.e. a function that takes an instance of a struct and creates similar instance with dummy field values:

p = Point(8.0, 11.0)
p2 = similar_struct(p)    # <-- like this
p2.x = 10.0
p2.y = 20.0

Currently I use:

p = Point(8.0, 10.0)
p2 = deepcopy(p)
p2.x = 10.0
p2.y = 20.0

But deepcopy is expensive and doesn’t work for all types.


Like this?

julia> mutable struct Point
           Point() = new()

julia> p = Point()
Point(#undef, #undef)

julia> p.x = 2

julia> p.y = 3

julia> p
Point(2, 3)

Or do you want to do it without having access to the inner constructor?


Yes, without any restrictions on a target type. I.e. user of this function should be able to use it for any mutable struct.

(However, thanks for the interesting trick - I didn’t know inner constructors may be used like this).