Struct inheritance in Julia

Viewed 786

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)?

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
Related