julia - 导入类型化函数
问题描述
我似乎无法导入带有类型参数的函数。幸运的是,我有一个最小的失败示例。
给定一个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
错误地导入了类型/结构?
解决方案
问题是您定义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.jl
和utils.jl
文件独立生活。然后你应该制作一个包,structs.jl
然后你可以将它加载到utils.jl
模块内部以及import_test.jl
外部范围内,Julia 会知道这Query
是相同的定义。Julia 手册中描述了实现此目的的步骤。
推荐阅读
- listview - Flutter中stack和listview的区别
- reactjs - 他为什么先
列表中的元素没有显示其他使用 React Bootstrap 的机器人? - c# - 在多个项目中为连接字符串使用外部配置文件
- java - 如何将数组列表中的值从 AsyncTask 类发送到 Android 中的另一个类?
- javascript - Angular ReferenceError:从 html 表单或按钮调用 typescript 函数
- android - 在android studio中打开新项目时android资源编译失败
- r - 按唯一标识符折叠多行,多个值(列),每个变量的多个元素(行)
- jquery - 获取每个 .class 的编号
- c++ - 为什么按值传递局部变量有效?
- c# - XPathNavigator 可以从测试输入中选择,但不能从真实输入中选择