我正在尝试使用以下布局创建一个包:
MyPkg
├── MyPkg.jl
├── Foo
│ ├── Foo.jl
│ └── another_file.jl
└── Bar
├── Bar.jl
└── yet_another_file.jl
我的主包模块如下所示:
# MyPkg.jl
module Pkg
include("./Foo/Foo.jl")
using .Foo: FooStuffA, FooStuffB
export FooStuffA, FooStuffB
include("./Bar/Bar.jl")
using .Bar: BarStruct, BarStuffC, BarStuffD
export BarStruct, BarStuffC, BarStuffD
end
问题出现在
Foo
需要在 struct
中定义的类型(特别是 Bar
)在一些函数参数中。我不确定如何导入这种类型。我似乎尝试了 include("../Bar/Bar.jl")
的所有组合, using Bar/.Bar/..Bar
,在 Foo
内子模块,子模块外等# Foo.jl
module Foo
# what am I missing here?
function print_bar_struct(bar::BarStruct)
@show bar
end
end
有什么建议吗?
最佳答案
这应该工作
# MyPkg.jl
module MyPkg
include("./Bar/Bar.jl")
using .Bar: BarStruct, BarStuffC, BarStuffD
export BarStruct, BarStuffC, BarStuffD
include("./Foo/Foo.jl")
using .Foo: FooStuffA, FooStuffB
export FooStuffA, FooStuffB
end
# Foo.jl
module Foo
using ..MyPkg: BarStruct
function print_bar_struct(bar::BarStruct)
@show bar
end
end
说明:请记住,包含语句本质上是将源文件中的代码复制+粘贴到给定行的模块中。因此,当编译器正在查看所有符号的引用时(从文件顶部读取到底部),
include("./Foo/Foo.jl")
发生时,它需要知道 BarStruct 存在并且可以在当前模块(即 MyPkg)中访问,它在这个重新排列的布局中。所以只要看看
MyPkg
的前半部分# MyPkg.jl
module MyPkg
include("./Bar/Bar.jl")
using .Bar: BarStruct, BarStuffC, BarStuffD
export BarStruct, BarStuffC, BarStuffD
当编译器到达这里的最后一行时,
BarStruct
, BarStuffC
, BarStuffD
是带入 MyPkg
的符号命名空间(https://docs.julialang.org/en/v1/manual/modules/#Summary-of-module-usage-1)。当我们到达
include("./Foo/Foo.jl")
行(此时也就是将此源文件复制 + 粘贴到当前模块中),我们需要引用 BarStruct
在此模块的父命名空间中,即 ..BarStruct
关于julia - Julia 中的子模块内部依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54410557/