How to simplify the code in constructing struct

I know the julia don’t have the “class”, but I need it. So I try to use struct to complete it. I try to implement the initialization of inheritance like following code.

struct P1
    M::Int8
    Ks::Int8
    metric::String
end

struct P2
    D::Int16
    Ds::Int16 
    k_v::Int64
    function P2(D,k_v)
        Ds = D*k_v
        new(D, Ds, k_v)
    end
end


struct C
    M::Int8
    Ks::Int8
    metric::String

    D::Int16
    Ds::Int16 
    k_v::Int64

    function C(M, Ks, metric, D, k_v)
        p1 = P1(M, Ks, metric)
        M, Ks, metric = p1.M, p1.Ks, p1.metric
        
        p2 = P2(D, k_v)
        D, Ds, k_v = p2.D, p2.Ds, p2.k_v 

        new(M, Ks, metric, D, Ds, k_v)
    end 
end

But I notice when the field of struct change, it is troublesome to adjust the code. I want to know the more reasonable ways to implement it.

Thanks in advance for any help/suggestion.

Why not just


struct C
    p1 :: P1
    p2 :: P2

    function C(M, Ks, metric, D, k_v)
        p1 = P1(M, Ks, metric)
        p2 = P2(D, k_v)
        new(p1, p2)
    end 
end

@Oscar_Smith It is ok. If I can access the field without the name of “parents”, I think it is better.

See this thread for related discussion. If you’re worried about the visual noise that results from accessing deeply nested fields, you may appreciate UnPack.jl.

2 Likes

@stillyslalom Thanks for your answer, It is very useful.

You might want to have a look at these packages:

3 Likes