Behavior of vector fields in mutable structures


#1

New to Julia and programming in general, sorry in advance for any faux pas. Here I define a structure S with a field f which expects a vector of integers.

 mutable struct S
     f::Vector{Int64}
     S(x) = new(x)
     end
end

Now I define two S structures, with the field of Sb taken from Sa

Sa = S([1,2])
Sb = S(Sa.f)

However, if I now change a value in Sb.f

Sb.f[1] = 3

the same change applies to Sa.f as well

Sa.f[1] == Sb.f[1]

returns true

Is this behavior intended? How would I change values in Sb.f without affecting Sa.f? My current workaround is simply

Sb = S(Sa.f + 0)

Am I doing something weird here?


#2

Yes, this is how julia works. After you do

x = [1, 2]
Sa = S(x)

x and Sa.f are the same vector in that they occupy the same physical memory. See also this post for an explanation of this (you can think of A and B in that post as your x and S.f).
If you want your type S to make a copy of the input you can define an inner constructor that copies:

mutable struct S
    f::Vector{Int}
    S(x) = new(copy(x))
end

#3

thank you!