Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a struct in julia

Tags:

copy

struct

julia

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
like image 235
Phuoc Avatar asked Aug 21 '18 21:08

Phuoc


1 Answers

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
like image 194
fredrikekre Avatar answered Oct 30 '22 07:10

fredrikekre