Search code examples
importmodulejuliaijulia-notebook

Using struct from a module inside another module in Julia


I have found similar questions on SO but none of them seem to give an answer that works for my case.

I have a few modules, in one of them I create a mutable struct which I want to be able to use in the others. All files are at the same level:

  • file_module_A.jl
  • file_module_B.jl
  • file_module_C.jl

In file_module_A.jl:

module A
   mutable struct MyType
      variable
   end
end

In file_module_B.jl:

module B
    # I need to import MyType here
end

In file_module_C.jl:

module C
    # I need to import MyType here
end

I have tried the followings without success:

  • Using directly: using .A doesn't work
  • I can't use: include("./file_module_A.jl") in both B and C because when they interact between each other I get the error can't convert from Main.B.A to Main.C.A since include includes a copy of the whole code

Any ideas? Thanks in advance!


Solution

  • You need to use using ..A. using .A means to look for A in the current module (B in the example below), and you need an extra . to step up one module level, to Main if you run the example in the REPL:

    module A
        mutable struct MyType
            variable
        end
    end
    
    module B
        using ..A: MyType
    end