Should `convert` include a type-assertion to ensure that the conversion succeeds?

For example, in badly inferred code, one may obtain

julia> @code_warntype (x -> convert(Int, x[1]))(Any[1])
MethodInstance for (::var"#3#4")(::Vector{Any})
  from (::var"#3#4")(x) @ Main REPL[5]:1
Arguments
  #self#::Core.Const(var"#3#4"())
  x::Vector{Any}
Body::Any
1 ─ %1 = Base.getindex(x, 1)::Any
│   %2 = Main.convert(Main.Int, %1)::Any
└──      return %2

However, the only sensible type that should be returned here is Int. With a type-assertion, we would obtain

julia> _convert(::Type{T}, x::T) where {T} = convert(T, x)::T
_convert (generic function with 1 method)

julia> @code_warntype (x -> _convert(Int, x[1]))(Any[1])
MethodInstance for (::var"#5#6")(::Vector{Any})
  from (::var"#5#6")(x) @ Main REPL[8]:1
Arguments
  #self#::Core.Const(var"#5#6"())
  x::Vector{Any}
Body::Int64
1 ─ %1 = Base.getindex(x, 1)::Any
│   %2 = Main._convert(Main.Int, %1)::Int64
└──      return %2

See some discussion in JuliaLang/julia#42372.

2 Likes