Type-casting arrays/vectors in Rust

前端 未结 1 533
北海茫月
北海茫月 2021-02-19 09:40

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];
le         


        
相关标签:
1条回答
  • 2021-02-19 09:52

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

    0 讨论(0)
提交回复
热议问题