首页 > 解决方案 > 导入类型化函数

问题描述

我似乎无法导入带有类型参数的函数。幸运的是,我有一个最小的失败示例。

给定一个Query定义在structs.jl

module Structs

export Query

struct Query
    name::String
    data::Int
end

end

dist还有一个使用这种类型的简单函数:

module Utils

include("structs.jl")
using .Structs: Query

export dist

function dist(x::Query, y::Query)
    return (x.data - y.data) ^ 2
end

end

为什么dist我调用它时找不到import_test.jl

include("structs.jl")
using .Structs: Query

include("utils.jl")
using .Utils: dist

a = Query("a", 1)
b = Query("b", -1)

println(dist(a, b))

相反,它失败并出现错误:

ERROR: LoadError: MethodError: no method matching dist(::Query, ::Query)
Stacktrace:
 [1] top-level scope at none:0
 [2] include at .\boot.jl:317 [inlined]
 [3] include_relative(::Module, ::String) at .\loading.jl:1041
 [4] include(::Module, ::String) at .\sysimg.jl:29
 [5] exec_options(::Base.JLOptions) at .\client.jl:229
 [6] _start() at .\client.jl:421
in expression starting at C:\Users\mr_bo\julia_test\import_test.jl:13

但是,如果我从dist函数中删除类型,使其变为function dist(x, y),则不再发生错误。

我是否Query错误地导入了类型/结构?

标签: julia

解决方案


问题是您定义Query了两次模块,它们是两个不同的模块。然后Query来自一个模块与Query来自另一个模块的不同。

你可以这样定义你想要的(我给出的例子没有include陈述,但你可以引入它们以获得相同的效果):

module Structs

export Query

struct Query
    name::String
    data::Int
end

end

module Utils

using ..Structs: Query

export dist

function dist(x::Query, y::Query)
    return (x.data - y.data) ^ 2
end

end

using .Structs: Query
using .Utils: dist

a = Query("a", 1)
b = Query("b", -1)
println(dist(a, b))

现在你可能会说你希望structs.jlutils.jl文件独立生活。然后你应该制作一个包,structs.jl然后你可以将它加载到utils.jl模块内部以及import_test.jl外部范围内,Julia 会知道这Query是相同的定义。Julia 手册中描述实现此目的的步骤。


推荐阅读