# Behavior of vector fields in mutable structures

**URL:** <https://discourse.julialang.org/t/behavior-of-vector-fields-in-mutable-structures/12583>\
**Category:** New to Julia\
**Created:** [July 22, 2018, 2:17pm UTC](https://discourse.julialang.org/t/behavior-of-vector-fields-in-mutable-structures/12583 "2018-07-22T14:17:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![KyleTDavid](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kyletdavid/32/6681_2.png) [@KyleTDavid](https://discourse.julialang.org/u/KyleTDavid)\
**Post date:** [July 22, 2018, 2:17pm UTC](https://discourse.julialang.org/t/behavior-of-vector-fields-in-mutable-structures/12583/1 "2018-07-22T14:17:28Z")

</div>

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.

```julia
 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

```julia
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?

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [July 22, 2018, 2:43pm UTC](https://discourse.julialang.org/t/behavior-of-vector-fields-in-mutable-structures/12583/2 "2018-07-22T14:43:07Z")

</div>

Yes, this is how julia works. After you do

```julia
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](https://discourse.julialang.org/t/converting-a-matlab-code-into-julia/12166/18) 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:

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

```

---

<div class="post-metadata">

**Author:** ![KyleTDavid](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kyletdavid/32/6681_2.png) [@KyleTDavid](https://discourse.julialang.org/u/KyleTDavid)\
**Post date:** [July 22, 2018, 6:10pm UTC](https://discourse.julialang.org/t/behavior-of-vector-fields-in-mutable-structures/12583/3 "2018-07-22T18:10:39Z")

</div>

thank you!
