Julia:结构体字段为Function向量时构造器触发MethodError求助
解决Julia中Vector{Function}构造器的MethodError问题
问题背景
定义了一个可变结构体Human,包含name::String和actions::Vector{Function}字段。使用仅接收actions字段的构造器时触发MethodError,但其他构造器和直接实例化正常工作。
示例代码
mutable struct Human name::String actions::Vector{Function} end Human_name_only(name::String, actions = Function[]) = Human(name, actions) Human_func_only(actions::Vector{Function}, name = "no_name") = Human(name, actions)
正常运行情况
julia> a = Human_name_only("paul") Human("paul", Function[]) julia> b = Human("paul", [f]) Human("paul", Function[f])
错误情况
julia> c = Human_func_only([f]) ERROR: MethodError: no method matching Human_func_only(::Vector{typeof(f)}) Closest candidates are: Human_func_only(::Vector{Function}) at c:\Users\reiva\Documents\Julia\Mtg\TEST.jl:12 Human_func_only(::Vector{Function}, ::Any) at c:\Users\reiva\Documents\Julia\Mtg\TEST.jl:12 Stacktrace: [1] top-level scope @ REPL[3]:1
问题原因
Julia中Vector{T}是不变类型,即Vector{typeof(f)}并不属于Vector{Function}的子类型,哪怕typeof(f) <: Function。构造器定义的参数类型是Vector{Function},而传入的[f]实际类型是Vector{typeof(f)},因此无法匹配方法签名。
解决方案
方法1:放宽构造器参数类型
将构造器的参数类型改为Vector{<:Function}(允许任意函数类型的向量),或者更通用的AbstractVector{<:Function}:
# 允许任意函数类型的Vector Human_func_only(actions::Vector{<:Function}, name = "no_name") = Human(name, actions) # 更灵活,支持所有函数类型的抽象向量 Human_func_only(actions::AbstractVector{<:Function}, name = "no_name") = Human(name, actions)
方法2:显式转换输入类型
调用构造器时,将传入的向量显式转换为Vector{Function}:
c = Human_func_only(Vector{Function}([f]))
方法3:构造器内部自动转换
在构造器内部完成类型转换,对外兼容更多输入类型:
Human_func_only(actions::AbstractVector{<:Function}, name = "no_name") = Human(name, convert(Vector{Function}, actions))
内容的提问来源于stack exchange,提问作者Xavier Lebeuf
相关产品推荐
相关产品推荐

