Custom structure constructor

Dear all,

I have a question about the use of custom constructor to initialize a Julia struct. I would like to initialize a parameter z (operational parameter) of a structure from some physical parameters, e.g. x and y. To clarify the problem, let’s consider the following code snippet

# ERROR
struct Foo
    z

    function Foo(x, y)
        self = new()
        self.z = x + y
       return self
    end
end

This code raises an error. To make it work, I need to declare the structure Foo as mutable, which is not desired proper, since z doesn’t mutate.

mutable struct Foo
    z

    function Foo(x, y)
        self = new()
        self.z = x + y
       return self
    end
end

What is the Julian way to do this (i.e. keep the structure immutable, while initializing it from external parameters) ?

Thank you for your answers.

This is the usual way to do something like that:

struct Foo
    z
    function Foo(x, y)
        self = new(x + y)
       return self
    end
end

I add the usual advice that it’s better in the long run to declare the struct so that z has a concrete or a parameterized type.

1 Like

Thank you for the answer. I will follow your advice :grinning:

I should have pointed you to the documentation about constructors. It’s probably worth reading. If there’s something you don’t understand, come back and ask.