Deep copy a `mutable struct` defined with an inner constructor

I’m in Julia 1.0.3, and I have a mutable struct

mutable struct MyStruct
    ID::Int64
    VAL::Float64
    function MyStruct(ID)
        b = new(ID)
        b.VAL = 0.0
    end
end

defined through an inner constructor. I want to deep-copy ms_A = MyStruct(1) into ms_B so that ms_B has the same values and fields as ms_A. However, my deep-copy function

Copy(x::T) where T = T([deepcopy(getfield(x, k)) for k ∈ fieldnames(T)]...)

can’t handle the inner-constructor. I’ve tried also adding an outer-constructor after my definition of MyStruct above

function MyStruct(ID, VAL)
    return MyStruct(ID, VAL)
end

but am still unable to deep copy. What’s the best way to approach this? Is there a way to still have the convenience constructor of only specifying ID in some cases and getting the full MyStruct with default VAL = 0 but also be able to copy each field?

Thanks!

The inner constructor is incorrect: it returns the value of b.VAL instead of the new object. You probably want something like this:

mutable struct MyStruct
    ID::Int64
    VAL::Float64
    function MyStruct(ID)
        b = new(ID, 0.0)
    end
end

In which case you can deep-copy an instance like this:

julia> ms_A = MyStruct(1)
MyStruct(1, 0.0)

julia> ms_B = deepcopy(ms_A)
MyStruct(1, 0.0)

julia> ms_A.ID = 42;

julia> ms_A
MyStruct(42, 0.0)

julia> ms_B
MyStruct(1, 0.0)
2 Likes

Thanks!