Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

type conversion - MethodError on adding items into Array of string pairs

I'm getting MethodError while doing very basic operation on Array of string pairs.

julia> arr = Array{Pair{string, string}}(undef, 1)
1-element Array{Pair{string,string},1}:
 #undef

julia> p = "str1" => "str2"
"str1" => "str2"

julia> push!(arr,p)
ERROR: MethodError: First argument to `convert` must be a Type, got string
Stacktrace:
 [1] convert(::Type{Pair{string,string}}, ::Pair{String,String}) at ./pair.jl:71
 [2] push!(::Array{Pair{string,string},1}, ::Pair{String,String}) at ./array.jl:934
 [3] top-level scope at REPL[103]:1

julia> arr[1] = p
ERROR: MethodError: First argument to `convert` must be a Type, got string
Stacktrace:
 [1] convert(::Type{Pair{string,string}}, ::Pair{String,String}) at ./pair.jl:71
 [2] setindex!(::Array{Pair{string,string},1}, ::Pair{String,String}, ::Int64) at ./array.jl:847
 [3] top-level scope at REPL[104]:1

Array of Int pairs doesn't seem to have this problem.

julia> arr2 = Array{Pair{Int, Int}}(undef, 1)
1-element Array{Pair{Int64,Int64},1}:
 0 => 0

julia> p2 = 1 => 2
1 => 2

julia> push!(arr2,p2)
2-element Array{Pair{Int64,Int64},1}:
 0 => 0
 1 => 2

julia> arr2[1] = p2
1 => 2

Am I missing something?

question from:https://stackoverflow.com/questions/65947550/methoderror-on-adding-items-into-array-of-string-pairs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Should be:

arr = Array{Pair{String, String}}(undef, 1)

The correctness of the parametric type seems to be checked once it is used in constructor and hence such improper data structure was allowed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...