我想浅复制一个结构以仅复制值,但将集合引用保留在其中。但是似乎没有内置方法:
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
答案 0 :(得分:2)
定义copy
对您自己的结构的意义,例如
Base.copy(s::S) = S(s.x, s.y)
似乎是您想要的。
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