Julia:将模块拆分成多个文件

k1n*_*ext 1 module julia

我正在使用Julia v0.6.4.考虑以下模块,保存在FooModule.jl:

module FooModule

export Foo
export doSomething

mutable struct Foo
    x::Int64
    function Foo(xin::Int64)
        new(xin)
    end # Foo
end # struct

function doSomething(F::Foo)
    println(F.x+123)
end # doSomething

end # module
Run Code Online (Sandbox Code Playgroud)

并且main.jl:

using FooModule
function main()
F = Foo(10)
doSomething(F)
end # main
Run Code Online (Sandbox Code Playgroud)

现在我开始Julia REPL:

julia> include("main.jl");

julia> main()
133
Run Code Online (Sandbox Code Playgroud)

即我得到了我的期望.现在想象doSomething包含许多行,我想分裂FooModule.jl.我想做这样的事情:

module FooModule

export Foo
export doSomething

include("doSomething.jl")        # <- include instead of writing out

mutable struct Foo
    x::Int64
    function Foo(xin::Int64)
        new(xin)
    end # Foo
end # struct

end # module
Run Code Online (Sandbox Code Playgroud)

doSomething.jl

function doSomething(F::Foo)
    println(F.x+123)
end # doSomething
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误,因为doSomething.jl一无所知Foo.

julia> include("main.jl");
ERROR: LoadError: LoadError: LoadError: UndefVarError: Foo not defined
Stacktrace:
 [1] include_from_node1(::String) at ./loading.jl:576
 [2] include(::String) at ./sysimg.jl:14
 [3] include_from_node1(::String) at ./loading.jl:576
 [4] eval(::Module, ::Any) at ./boot.jl:235
 [5] _require(::Symbol) at ./loading.jl:490
 [6] require(::Symbol) at ./loading.jl:405
 [7] include_from_node1(::String) at ./loading.jl:576
 [8] include(::String) at ./sysimg.jl:14
while loading ~/Desktop/doSomething.jl, in expression starting on line 1
while loading ~/Desktop/FooModule.jl, in expression starting on line 6
while loading ~/Desktop/main.jl, in expression starting on line 1
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

fre*_*kre 6

只需移动include("doSomething.jl")到函数最初的位置,即类型定义之后.您可以include将代码视为将代码复制粘贴到文件中.