How to copy all fields without changing the referece?

If you’re worried about speed, you could create the copy! function with a macro at type creation.

I needed something similar, so generated copy! function with following.
You might be able to model something for you use case.


function CompositeCopy!(T::Symbol)
    dataType = eval(current_module(), T)
    fieldNames = fieldnames(dataType)
    fieldTypes = dataType.types
    expressions = Array(Expr, numFields)

    for i = 1 : length(fieldNames)
        fieldName = fieldNames[i]
        fieldType = fieldTypes[i]
        @assert fieldType.mutable == method_exists(copy!, (fieldType, fieldType))

        if method_exists(copy!, (fieldType, fieldType))
            expressions[i] = :(copy!(x.$fieldName, y.$fieldName))
        else
            expressions[i] = :(x.$fieldName = y.$fieldName)
        end
    end

    body = Expr(:block, expressions...)

    quote
        function Base.copy!(x::$T, y::$T)
            $body
            return x
        end
    end
end