Type cast array / vector in rust

What is the usual way to convert an array or vector 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 I can implement the same in a more concise way, similar to scalar type conversion

I can't seem to find a clue in rust manual or reference materials TIA.

Solution

In general, the best you will get is the same as what you have (this assigns 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);

Although, if you know that the bit pattern of what you project is the same (for example, the newtype structure of the type it contains, or the conversion between uint and int), you can make an in place conversion without assigning a new vector (although this means that the old x cannot be accessed):

let x = ~[0i,2];
let y: ~[uint] = unsafe { cast::transmute(x) };

(please note that this is unsafe and may lead to bad things.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>