【发布时间】:2019-10-01 04:20:42
【问题描述】:
在 Julia 文档手册中,它说以下 [1]:
什么时候调用转换?
以下语言结构调用转换:
- 分配给数组会转换为数组的元素类型。
[1]https://docs.julialang.org/en/v1/manual/conversion-and-promotion/#When-is-convert-called?-1
我已经定义了以下代码:
julia> abstract type Element end
julia> abstract type Inline <: Element end
julia> struct Str <: Inline
content::String
end
julia> convert(::Type{Str}, e::String) = Str(e)
convert (generic function with 1 method)
julia> convert(::Type{Element}, e::String) = convert(Str, e)
convert (generic function with 2 methods)
我为 Julia 类型 String 定义了 convert。从String 类型的实例转换为Element 和转换为Str 可以按预期工作。但是,以下失败:
julia> convert(Str, "hi")
Str("hi")
julia> convert(Element, "hi")
Str("hi")
julia> arr = Element[]
0-element Array{Element,1}
julia> push!(arr, "hi")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Element
Closest candidates are:
convert(::Type{T}, ::T) where T at essentials.jl:168
Stacktrace:
[1] push!(::Array{Element,1}, ::String) at ./array.jl:866
[2] top-level scope at REPL[25]:1
julia> arr = Str[]
0-element Array{Str,1}
julia> push!(arr, "hi")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Str
Closest candidates are:
convert(::Type{T}, ::T) where T at essentials.jl:168
Str(::String) at REPL[19]:2
Str(::Any) at REPL[19]:2
Stacktrace:
[1] push!(::Array{Str,1}, ::String) at ./array.jl:866
[2] top-level scope at REPL[27]:1
julia>
有人可以解释为什么上述失败了吗?如果可能的话,如何防止它失败?
【问题讨论】:
标签: julia