Struct 调用参数化结构的构造函数时发生MethodError
我正试图在Julia中创建一个链接列表。 我有: 现在,上面的代码编译得很好。我还可以运行:Struct 调用参数化结构的构造函数时发生MethodError,struct,julia,Struct,Julia,我正试图在Julia中创建一个链接列表。 我有: 现在,上面的代码编译得很好。我还可以运行:x=LLNode(0,nothing,nothing)fine。但是当我运行y=LinkedList(0,nothing,nothing)时,我得到一个no方法匹配LinkedList(::Int64,::Void,::Void)错误。有什么好处 VERSION返回v“0.6.2”原因是LinkedList需要参数T。如果将nothing作为第二个和第三个参数传递,朱莉娅就无法推断T是什么 因此,您必须明
x=LLNode(0,nothing,nothing)
fine。但是当我运行y=LinkedList(0,nothing,nothing)
时,我得到一个no方法匹配LinkedList(::Int64,::Void,::Void)
错误。有什么好处
VERSION
返回v“0.6.2”
原因是LinkedList
需要参数T
。如果将nothing
作为第二个和第三个参数传递,朱莉娅就无法推断T
是什么
因此,您必须明确指定它,例如:
julia> LinkedList{Int}(0, nothing, nothing)
LinkedList{Int64}(0, nothing, nothing)
或者传递第二个和/或第三个参数,允许推断T
,例如使用x
:
julia> LinkedList(0, x, x)
LinkedList{Int64}(0, LLNode{Int64}(0, nothing, nothing), LLNode{Int64}(0, nothing, nothing))
作为旁注——您可能想查看一个相当完整的链表实现的示例。当您编写
LLNode(0,nothing,nothing)
时,Julia能够发现它需要根据第一个参数的类型构造LLNode{Int}
。但是在LinkedList(0,nothing,nothing)
中,它实际上没有什么可以决定类型参数应该是什么,所以它不知道构造什么
相反,您需要明确地选择您想要的T
:
julia> LinkedList{Int}(0, nothing, nothing)
LinkedList{Int64}(0, nothing, nothing)
或者,它可以基于非空参数获取T
:
julia> LinkedList(0, LLNode(0, nothing, nothing), nothing)
LinkedList{Int64}(0, LLNode{Int64}(0, nothing, nothing), nothing)
谢谢你的链接。事实证明,它有很多处理参数化结构的有用(和惯用!)示例。我建议将此链接与您的链接结合起来,以供其他想要学习参数化结构的初学者使用。
julia> LinkedList(0, LLNode(0, nothing, nothing), nothing)
LinkedList{Int64}(0, LLNode{Int64}(0, nothing, nothing), nothing)