Referencing the same module from multiple files

Reproducible code

I created 3 files like

# useful.jl
module Useful  # issue
struct UsefulStruct 
    data
end
end
# create.jl
module Create
include("useful.jl")

function create()::Useful.UsefulStruct
    Useful.UsefulStruct(1)
end
end
# calculate.jl
module Calculate
include("useful.jl")
include("create.jl")

calculate(s::Useful.UsefulStruct) = s.data * 2
end

in a directory, ran

include("create.jl")
include("calculate.jl")

Calculate.calculate(
    Create.create()
)

and got following error.

ERROR: LoadError: MethodError: no method matching calculate(::Main.Create.Useful.UsefulStruct)
Closest candidates are:
  calculate(::Main.Calculate.Useful.UsefulStruct) at /...

Question

I thought I was using the same UsefulStruct, but it is recognized as something different.
What should I do if I want to do these things?

1 Like

Welcome to our community! :confetti_ball:

This problem is frequent among novice Julia programmers and was already asked multiple times in this forum. (But I concede that the search utility of Discourse never finds any useful results, even when I know they exist.) See:

Basically, the rule is: include once and import whenever necessary.

Your topmost module should include all files a single time and you should use import/using relative to it (using .MyModule refers to a module defined in the current module, using ..MyModule refers to a module define in the parent module, i.e., a sibling module, and you can do something like using ...MyModule.A.B to go to the parent of the parent and then go down to a specific submodule). In your case, if you include Useful and Create inside Calculate you want to replace the include("useful.jl") inside Create by import ..Useful

9 Likes

Thank you for your polite and kind reply!
It solved my problem.

5 Likes