kev*_*818 5 dependency-management julia
我正在尝试创建具有以下布局的包:
\n\nMyPkg\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 MyPkg.jl\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Foo\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Foo.jl\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 another_file.jl\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Bar\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Bar.jl\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 yet_another_file.jl\nRun Code Online (Sandbox Code Playgroud)\n\n我的主包模块看起来像这样:
\n\n# MyPkg.jl\nmodule Pkg\n\ninclude("./Foo/Foo.jl")\nusing .Foo: FooStuffA, FooStuffB\nexport FooStuffA, FooStuffB\n\ninclude("./Bar/Bar.jl")\nusing .Bar: BarStruct, BarStuffC, BarStuffD\nexport BarStruct, BarStuffC, BarStuffD\n\nend\nRun Code Online (Sandbox Code Playgroud)\n\n当需要在某些函数参数中定义Foo类型(特别是 a )时,就会出现问题。我不知道如何导入这种类型。我似乎已经尝试了子模块内部、子模块外部等的所有组合。structBarinclude("../Bar/Bar.jl")using Bar/.Bar/..BarFoo
# Foo.jl\nmodule Foo\n\n# what am I missing here?\n\nfunction print_bar_struct(bar::BarStruct)\n @show bar\nend\n\nend\nRun Code Online (Sandbox Code Playgroud)\n\n有什么建议吗?
\n这应该有效
# 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
Run Code Online (Sandbox Code Playgroud)
# Foo.jl
module Foo
using ..MyPkg: BarStruct
function print_bar_struct(bar::BarStruct)
@show bar
end
end
Run Code Online (Sandbox Code Playgroud)
说明:请记住,include 语句本质上是将源文件中的代码复制并粘贴到给定行的模块中。因此,当编译器查看所有符号的引用(从文件顶部到底部读取)时,在include("./Foo/Foo.jl")发生的地方,它需要知道 BarStruct 存在并且可以在当前模块中访问(即 MyPkg),它就是在这个重新排列的布局中。
所以只要看看前半部分MyPkg
# MyPkg.jl
module MyPkg
include("./Bar/Bar.jl")
using .Bar: BarStruct, BarStuffC, BarStuffD
export BarStruct, BarStuffC, BarStuffD
Run Code Online (Sandbox Code Playgroud)
当编译器到达这里的最后一行时,BarStruct, BarStuffC,BarStuffD是带入命名空间的符号MyPkg(https://docs.julialang.org/en/v1/manual/modules/#Summary-of-module-usage-1) 。
当我们到达该include("./Foo/Foo.jl")行时(此时也称为将此源文件复制+粘贴到当前模块中),我们需要BarStruct在此模块的父命名空间中引用,即..BarStruct