I would like to shallow copy a struct to copy only values but keep the collection references in it. But there seems to be no builtin method for it:
julia> mutable struct S
x
y
end
julia> a = S(1, rand(2))
S(1, [0.792705, 0.582458])
julia> b = deepcopy(a)
S(1, [0.792705, 0.582458])
julia> b.y === a.y
false
julia>
julia> b = copy(a)
ERROR: MethodError: no method matching copy(::S)
Closest candidates are:
copy(::Expr) at expr.jl:36
copy(::BitSet) at bitset.jl:46
copy(::Markdown.MD) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v0.7/Markdown/src/parse/parse.jl:30
...
Stacktrace:
[1] top-level scope at none:0
julia> b.y === a.y # expect true
Define what copy
should mean for your own struct, e.g.
Base.copy(s::S) = S(s.x, s.y)
seems to be what you want.
julia> mutable struct S
x
y
end
julia> Base.copy(s::S) = S(s.x, s.y)
julia> a = S(1, rand(2));
julia> b = copy(a);
julia> a.y === b.y
true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With