Trying to require Modules in a circular way, program just crashes

I got 2 files, and in each file I include` the other file so it goes like


When I run this code it just errors hard:

Is there any way around it?

There is probably a better way to do what you want, you just have to explain it.

Also, please quote your code:

1 Like

Are you trying to emulate some OO-style by using modules? Anyway, here’s how you can do it if you want to define the actual types in different modules.

In file TwoFiles.jl I have

abstract type AbstractClient end
abstract type AbstractManager end

include("client.jl")
include("manager.jl")

println("Yay! 🍕 for everyone!")

In file client.jl I have

module JClient
    import ..AbstractClient, ..AbstractManager
    export self

    struct self{TM<:AbstractManager}<:AbstractClient
        token::String
        ws::TM
    end
end

and in file manager.jl I have

module WSManager
    import ..AbstractClient, ..AbstractManager
    export Manager

    struct Manager{C<:AbstractClient} <: AbstractManager
        client::C
    end
end

this gives

So using abstract types can get around the fact that the two modules don’t know about each others types directly.

Edit: I should say it doesn’t do exactly what you had, obviously those fields can now also take other AbstractClient types and AbstractManager types, but…

Oh wow thank you very much

Another question, can I access the fields when I pass them to the struct?

I don’t understand what you mean. What did you try?

I think OP wanted to afterwards create instances with circular (i.e. mutual) references, such that some_client.ws.client === some_client. Such a thing is afaik currently impossible, because julia currently does not support forward definitions of types.

Apart from the problem that, without having one of them mutable, you would not be able to construct such instances (and if you cheat and construct recursive immutable structs by pointer manipulation then you are likely to cause a crash).

Creating two immutable objects that refer to each other is a bit of a chicken and egg problem.

3 Likes