Changing the field value inside the structure

Hi everyone,

I have some structure with only one field. Is it possible to declare some function inside this structure that use field variable and change its components.

For example I have following code:

using Parameters

@with_kw struct MyStruct
    A::Matrix{Int64} = zeros(2, 2)

    function MyStruct( )
        A[1, 1] = 1


mystruct = MyStruct()

I want to directly use the matrix A defined within the structure and change its values. Can I do something like this : MyStruct.A[1, 1] = 1 ?

Do myStruct.A[1, 1] = 1. Note that Mystruct (capital) is the type.

1 Like

I’m a little confused about your question. Let’s start with

struct MyStruct
  A :: Matrix{Int}

and the constructor (no need to make that an inner constructor):

function MyStruct()
      s = MyStruct(zeros(2,2));
      s.A[1,1] = 1;
      return s

so that

julia> s1 = MyStruct()
MyStruct([1 0; 0 0])

Now you can of course define

set_a1(s :: MyStruct, x) = s.A[1,1] = x

julia> set_a1(s1, 5)

Functions other than inner constructors are not defined inside the struct (unlike OOP). Not sure if that answers your question, but it may help to clarify what you are looking for.

1 Like

As @PetrKryslUCSD said, once you’ve constructed an instance mystruct of the Type MyStruct, you can manipulate its field A using mystruct.A.

It won’t bite you here, but worth noting a “gotcha” just in case: generally, if you want to be able to change the values stored in a struct, you want to define it as a mutable struct. If field A were not a Matrix, say an Int64 instead, then you’d get errors when trying to change its value. In your given case, it still works without the mutable keyword only because (under the hood) structs store Matrix types using only a Ref pointer to the location in memory of their contents; changing the Matrix contents doesn’t necessarily change the Ref held by the struct.


Good point! Put differently, if the field itself is a mutable object, it can still be modified even if it is contained in a normal (immutable) struct, but to change the value of an immutable field, a mutable struct is necessary.

Can’t you just write

@with_kw struct MyStruct
    A::Matrix{Int64} = [1 0; 0 0]