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
end
end
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 ?
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.
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.