拉斯特型铸造阵列/矢量 [英] Type-casting arrays/vectors in Rust
问题描述
什么是拉斯特阵列或一种类型的媒介转换到另一种惯用的方法吗?所需的效果是
What would be the idiomatic way of converting arrays or vectors of one type to another in Rust? The desired effect is
let x = ~[0 as int, 1 as int, 2 as int];
let y = vec::map(x, |&e| { e as uint });
但我不知道,如果同样的能够在一个更加简洁时尚,类似于标量类型强制转换来实现。
but I'm not sure if the same could be achieved in a more concise fashion, similar to scalar type-casts.
我似乎在发现了锈病手动或参考的线索失败。 TIA。
I seem to fail at finding clues in the Rust manual or reference. TIA.
推荐答案
在一般情况下,你会得到最好的就是类似于你有什么(这个分配一个新的向量):
In general, the best you are going to get is similar to what you have (this allocates a new vector):
let x = ~[0i, 1, 2];
let y = do x.map |&e| { e as uint };
// equivalently,
let y = x.map(|&e| e as uint);
尽管如此,如果你知道你的铸造事情位模式是相同的(如NEWTYPE结构给它缠上,或 UINT
间铸造的类型和 INT
),你可以做一个就地投,不会分配一个新的载体(尽管它意味着老 X
无法访问):
Although, if you know the bit patterns of the things you are casting between are the same (e.g. a newtype struct to the type it wraps, or casting between uint
and int
), you can do an in-place cast, that will not allocate a new vector (although it means that the old x
can not be accessed):
let x = ~[0i, 1, 2];
let y: ~[uint] = unsafe { cast::transmute(x) };
(注意,这是不安全
,并可能导致坏事情发生。)
(Note that this is unsafe
, and can cause Bad Things to happen.)
这篇关于拉斯特型铸造阵列/矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!