Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a constructor for a struct in Julia?

Tags:

julia

I have recently started to do object-oriented stuff in Julia and have enjoyed using structs (the Python equivalent to a class?).

I read the documentation about structs here, but I did not see anything about constructors or methods in the struct. I have seen structs used a few places where someone actually defines a function inside of the struct. How can I do that and why would you want to do that?

like image 893
logankilpatrick Avatar asked Dec 06 '19 18:12

logankilpatrick


1 Answers

When you finish reading carefully the documentation suggested by StefanKarpinski (and it is really good), have a look for the Parameters package which, in my opinion, makes the object-oriented transformation to Julia much nicer.

Have a look at this code:

@with_kw mutable struct Agent
    age = 0
    income = rand()
end

function Agent(age::Int)
    income = rand()+age*10
    Agent(age, income)
end

And now some usages:

julia> Agent()
Agent
  age: Int64 0
  income: Float64 0.28109332504865625


julia> Agent(income=33)
Agent
  age: Int64 0
  income: Int64 33


julia> Agent(age=3)
Agent
  age: Int64 3
  income: Float64 0.5707873066917069


julia> Agent(30)
Agent
  age: Int64 30
  income: Float64 300.1706559468855

The last constructor was the custom-made one, while the three previous were automatically generated by the @withkw macro.

Last, but not least. Consider a loop reference data structure, i.e., where AgentY1 can only have friends of type AgentY2 and AgentY2 can only have friends of type AgentY1:

To my best knowledge (maybe someone can correct me if I am wrong) this can be only achieved using the macro:

@with_kw mutable struct AgentY1
    age::Int
    friends=AgentY2[]
end


@with_kw mutable struct AgentY2
    age::Int
    friends=AgentY1[]
end

And now sample usage:

julia> aa = AgentY1(age=11)
AgentY1
  age: Int64 11
  friends: Array{AgentY2}((0,))

This is how I do my OO programming in Julia.

like image 109
Przemyslaw Szufel Avatar answered Oct 19 '22 16:10

Przemyslaw Szufel