【发布时间】:2020-04-17 14:41:01
【问题描述】:
假设我有一个模块,Module1 定义了一个结构和一个 fit() 函数。我有另一个模块,称为 Parent,它包括 Module1 并定义了一个 test() 函数,该函数也调用 fit()。如果我从模块 1 定义结构,然后从 Parent 调用 test(),我会遇到命名空间问题。下面是这个例子的代码:
#this module would be in a separate file
module Module1
struct StructMod1
end
export StructMod1
function fit(s::StructMod1)
end
export fit
end
module Parent
#including the module with include("Module1.jl")
module Module1
struct StructMod1
end
export StructMod1
function fit(s::StructMod1)
end
export fit
end
#including the exports from the module
using .Module1
function test(s::StructMod1)
fit(s)
return s
end
export test
end
using .Parent, .Module1
s = Parent.Module1.StructMod1()
@show test(s)
s2 = StructMod1()
@show test(s2)
还有输出
test(s) = Main.Parent.Module1.StructMod1()
ERROR: LoadError: MethodError: no method matching test(::StructMod1)
Closest candidates are:
test(::Main.Parent.Module1.StructMod1)
或者,如果我将 using .Module1 替换为 using ..Module1,则 s2 的定义有效。但是,当使用 .Parent 调用时,我必须确保 Module1 已经加载。
用一个模块定义结构然后将其与另一个模块的函数一起使用的最佳方法是什么?
【问题讨论】:
标签: struct module namespaces load julia