Solving a cyclic include dependency in Julia

Viewed 38

Suppose the following (it is supposed to be like a typical Julia package):

pkg.jl
module pkg
    include("a.jl")
    include("b.jl")
end  # module
a.jl
struct A
    a
end  # struct

function use_B(obj::B)
    return obj.b
end  # function
b.jl
struct B
    b
end  # struct

function use_A(obj::A)
    return obj.a
end  # function

Notice that pkg.jl imports a.jl first. If I run the file, it gives me an UndefVarError because the use_B() function in a.jl doesn't know what B is.

If I import b.jl first in pkg.jl, it also gives me an UndefVarError, now because the use_A() function in b.jl doesn't know what A is.

What is the best way to solve this problem?


P.S. I would like to know a solution that does not require me to move use_A() or use_B() to a different file.

1 Answers
Related