我想要对一个结构体进行浅复制,仅复制其值但保留其中的集合引用。但似乎没有内置方法来完成此操作:
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
Base.copy(x::T) where T = T([getfield(x, k) for k ∈ fieldnames(T)]...)
函数,可以复制任何类型的对象。 - PhuocBase.copy(x::T) where T = T([deepcopy(getfield(x, k)) for k ∈ fieldnames(T)]...)
的目的是什么? - jjjjjj