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

**URL:** https://discourse.julialang.org/t/should-convert-include-a-type-assertion-to-ensure-that-the-conversion-succeeds/85577
**Category:** Internals & Design
**Tags:** base, type-stability
**Created:** [August 10, 2022, 9:05am UTC](https://discourse.julialang.org/t/should-convert-include-a-type-assertion-to-ensure-that-the-conversion-succeeds/85577 "2022-08-10T09:05:09Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![jishnub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jishnub/32/33620_2.png) [@jishnub](https://discourse.julialang.org/u/jishnub)
#### Post date: [August 10, 2022, 9:05am UTC](https://discourse.julialang.org/t/should-convert-include-a-type-assertion-to-ensure-that-the-conversion-succeeds/85577/1 "2022-08-10T09:05:10Z")

</div>

> <https://github.com/JuliaLang/julia/blob/f1b968d68f8466875fa11a1af7fc3689986c65c0/base/Base.jl#L64>

For example, in badly inferred code, one may obtain

```julia
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
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

```

---

<div class="post-metadata">

### Author: ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)
#### Post date: [August 10, 2022, 9:41am UTC](https://discourse.julialang.org/t/should-convert-include-a-type-assertion-to-ensure-that-the-conversion-succeeds/85577/2 "2022-08-10T09:41:02Z")

</div>

See some discussion in [JuliaLang/julia#42372](https://github.com/JuliaLang/julia/issues/42372).
