julia - Julia 中的子模块内部依赖

标签 julia dependency-management

我正在尝试使用以下布局创建一个包:

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/

相关文章:

julia - 如何轻松检查Julia语言中嵌入函数的实现?

android - .so 模块中定义的文件不会成为最终 APK 的一部分

java - 导入并使用 Maven 管理的 Java 库 (CitySDK)

java - 如何管理maven子项目不在同一目录结构?

java - Stanford-CoreNLP 和 Stanford-Parser 中的 Maven 类名冲突

julia - 如何在Julia中读取gzip压缩的CSV文件?

python - 在 Python 脚本中运行 Julia 文件

julia - 如何简洁地计算 Julia 数组中行项的差异百分比

python - 在 Common Lisp 中管理依赖关系

matrix - 访问 Julia 矩阵中的任意行