Hello, I’m new to Julia. I am writing an application that is divided up into several modules, but I’m having trouble figuring out how to incorporate those modules with each other. In particular, I have some data structure definitions like these:
const RealVec{T<:Real} = Array{T}
struct Particles
m::RealVec
q::Array{RealVec}
p::Array{RealVec}
end
And I would like to share these definitions between all of the modules without redefining them in each module.
What’s the best way to do this? Should I put the definitions in a defs.jl file and use include statements at the top of each module that uses the definitions? Or should I put the definitions in a module called (for ex) “defs” and then export those definitions from the module and then put “using defs” at the top of each other module? Or something else?
Thank you for any guidance.
Mark
2 Likes
Hello, and welcome to Julia!
Regarding your question: have you thought about idea not to use modules at all? Unlike python or other similar languages Julia is less restrictive and it is quite common to wrap all package in one single module and plainly include all other files. It helps multiple dispatch and minimize number of issues like yours.
But if you insist on using modules, then you can do the following: define your structure in one of the module and then you can import it with the help of using and ..
syntax. When you are prepending .
, ..
, ...
before the name of the module, it is similar to navigation in file system, so ..
means “module which is defined in parent module”.
So it will look like this
# file defs.jl
module A
struct Foo end
end # module
# file misc.jl
module B
using ..A: Foo
x = Foo()
end
# file main.jl
include("defs.jl")
include("misc.jl")
Thirdly, your structure uses abstract types (Array
is an abstract type), so it’s better to change it to a concrete type or you can hurt perfrormance. See Performance tips for more info.
Fourthly, please, when you are posting in discourse, close your code in triple backticks: item 2 of "make it easier to help you.
5 Likes
Thank you for your helpful response!
have you thought about idea not to use modules at all?
I had considered that and was starting to think it makes more sense to do it that way. Thank you for mentioning that.
( Array
is an abstract type)
I didn’t realize that, thank you for pointing it out.
close your code in triple backticks
I intended to do this but somehow messed it up! I’ve fixed it in my original post.
Thank you,
Mark
3 Likes