Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I seem to fail at finding clues in the Rust manual or reference. TIA.

like image 549
Arets Paeglis Avatar asked May 26 '13 00:05

Arets Paeglis


People also ask

What is a VEC in Rust?

The Vec type allows to access values by index, because it implements the Index trait. An example will be more explicit: let v = vec![ 0, 2, 4, 6]; println!(" {}", v[1]); // it will display '2'

Are vectors contiguous Rust?

Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents.


1 Answers

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);

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.)

like image 156
huon Avatar answered Sep 23 '22 17:09

huon