# How to copy all fields without changing the referece?

**URL:** <https://discourse.julialang.org/t/how-to-copy-all-fields-without-changing-the-referece/945>\
**Category:** General Usage\
**Created:** [December 14, 2016, 3:33pm UTC](https://discourse.julialang.org/t/how-to-copy-all-fields-without-changing-the-referece/945 "2016-12-14T15:33:27Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![greg\_plowman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/greg_plowman/32/8100_2.png) [@greg\_plowman](https://discourse.julialang.org/u/greg_plowman)\
**Post date:** [December 14, 2016, 8:54pm UTC](https://discourse.julialang.org/t/how-to-copy-all-fields-without-changing-the-referece/945/5 "2016-12-14T20:54:25Z")

</div>

> 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.

```julia

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

```

---

_[View the full topic](https://discourse.julialang.org/t/how-to-copy-all-fields-without-changing-the-referece/945)._
