Let's say I have a vector
v = Any[1,2,3,4]
And I would like to recompute its eltype in such a way that
typeof(v) = Vector{Int}
Is it possible to accomplish this without having to manually concatenate each of the elements in v
?
Let's say I have a vector
v = Any[1,2,3,4]
And I would like to recompute its eltype in such a way that
typeof(v) = Vector{Int}
Is it possible to accomplish this without having to manually concatenate each of the elements in v
?
You can't "retype" the existing
v
, just create a copy of it with the more concrete type1.转换次数
假设您已经(静态地)知道结果类型,则有多种选择。最易读的(和IMO,惯用的)是
我认为这相当于
或者:
转换成什么
If you don't know what the "common type" would be, there are multiple options how to get one that matches. In general, typejoin can be used to find a least upper bound:
The result will most likely be abstract, e.g.
Real
for an array ofInt
s andFloat64
s. So, for numeric types, you might be better off withpromote_type
:This at least gives you
Float64
for mixedInt
s andFloat64
s.但是,实际上并不建议所有这些方法,因为它可能很脆弱,令人惊讶,并且类型不稳定。
1For certain combinations of types,
reinterpret
will work and return a view with a different type, but this is only possible for bits types, whichAny
is not. For convertingAny[1,2,3]
toInt[1,2,3]
copying is fundamentally necessary because the two arrays have different layouts in memory: the former is an array of pointers to individually allocated integers objects, whereas the latter stores theInt
values inline in contiguous memory.