Cannot convert despite convert method being defined

I have the following sample code:

struct Bar
    b:: Int64
end

convert(::Type{Bar}, x::Int64) = Bar(x)


struct Foo
    b::Bar
end

I execute it in the REPL. I then write

f = Foo(1)

I expect it to work because I have defined how to implicitly convert from and Int64 to Bar. However I get the error:

ERROR: MethodError: Cannot convert an object of type Int64 to an object of type Bar

Why doesn’t this work?

Base.convert(::Type{Bar}, x::Int64) = Bar(x)

You were creating a new function called convert instead of adding a method to Base.convert. You either need to fully qualify the function name or do import Base: convert first.

2 Likes