I have two types A
and B
. I have written B(a::A)
and convert(::Type{B}, a)
, but this does not immediately make Array{B}(as::Array{A})
work. Must I write this method as well? According to the documentation, I would expect Julia would handle the rest for me.
struct A end
struct B end
B(a::A) = B();
convert(::Type{B}, a) = B(a);
# These work
B(A());
convert(B, A());
# This doesn't
Array{B}([A()]);
This is the error
ERROR: LoadError: MethodError: Cannot `convert` an object of type A to an object of type B
Closest candidates are:
convert(::Type{T}, !Matched::T) where T at essentials.jl:154
B(::A) at /home/mvarble/test.jl:3
Stacktrace:
[1] setindex!(::Array{B,1}, ::A, ::Int64) at ./array.jl:767
[2] copyto! at ./abstractarray.jl:753 [inlined]
[3] copyto! at ./abstractarray.jl:745 [inlined]
[4] Type at ./array.jl:482 [inlined]
[5] Array{B,N} where N(::Array{A,1}) at ./boot.jl:427
[6] top-level scope at none:0
[7] include at ./boot.jl:326 [inlined]
[8] include_relative(::Module, ::String) at ./loading.jl:1038
[9] include(::Module, ::String) at ./sysimg.jl:29
[10] exec_options(::Base.JLOptions) at ./client.jl:267
[11] _start() at ./client.jl:436
You have to add a method to convert
from Base, and not define a new convert
function in the current module. Therefore you should write:
Base.convert(::Type{B}, a) = B(a)
or
import Base: convert
before defining convert
as you did in your code.
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras