Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct inheritance in Julia

Tags:

julia

Given I have some struct:

julia> struct Car
           wheels::Int64
           engine::Int64
           model::String
       end

Is there a way I can make a new struct and inherit the the attributes of the Car I defined above (similar to class inheritance in Object Orientated Programming)?

like image 868
logankilpatrick Avatar asked Jun 25 '26 03:06

logankilpatrick


1 Answers

Take a look at this discussion and this answer.

The best way to achieve such behaviour is to access struct members from functions rather than directly accessing fields, and just use composition for your struct.

Then you can use a forwarding macro. e.g:

using ReusePatterns

struct Car
    wheels::Int64
    engine::Int64
    model::String
end

wheels(c::Car) = c.wheels
engine(c::Car) = c.engine
model(c::Car) = c.model

struct DoorCar
    car::Car
    doors::Int64
end

@forward (DoorCar, :car) Car
like image 126
Joaquín Avatar answered Jun 27 '26 04:06

Joaquín



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!