Modify attribute of mutable struct from within

I would like to have a function inside of a mutable struct that is able to modify the value of the attributes from the struct when called.
As a test, I tried a simple

mutable struct Test
    a
    b
    function init_test()
        print(a)
        a = 5
        print(a)
    end
    init_test()
end
t = Test(3,3)

However this returns :

ERROR: LoadError: UndefVarError: a not defined

I searched through the doc, github and the forum but didn’t find any way to do this, which is surprising since it seems to be something quite basic. What am I doing wrong ?

  1. init_test runs when the type is defined, not when an object of the type is created (instanciated). So your code is running at the wrong time.
  2. There’s no way to implicitly refer a field. This isn’t like c++. You always need an object to explicitly refer to the field. You simply need a normal function to set the field if that’s what you want to do.
  3. And the function that’ll automatically run when you call the type, well, is type itself. You just need to overload it. And it’s called constructor.
1 Like

maybe you want this behavior?

julia> mutable struct Test
           a
           b
           function Test(a,b)
               print(a)
               new(5,b)
           end
       end

julia> t = Test(3,3)
3Test(5, 3)

https://docs.julialang.org/en/v1/manual/constructors/#man-inner-constructor-methods-1

1 Like