Is there a good way to convert a Vec to an array?

前端 未结 1 1591
孤城傲影
孤城傲影 2020-12-06 08:58

Is there a good way to convert a Vec with size S to an array of type [T; S]? Specifically, I\'m using a function that returns

相关标签:
1条回答
  • 2020-12-06 09:32

    As of Rust 1.48:

    use std::convert::TryInto;
    
    fn demo<T>(v: Vec<T>) -> [T; 4] {
        v.try_into()
            .unwrap_or_else(|v: Vec<T>| panic!("Expected a Vec of length {} but it was {}", 4, v.len()))
    }
    

    Before that:

    use std::convert::TryInto;
    
    fn demo<T>(v: Vec<T>) -> [T; 4] {
        let boxed_slice = v.into_boxed_slice();
        let boxed_array: Box<[T; 4]> = match boxed_slice.try_into() {
            Ok(ba) => ba,
            Err(o) => panic!("Expected a Vec of length {} but it was {}", 4, o.len()),
        };
        *boxed_array
    }
    

    Arrays must be completely initialized, so you quickly run into concerns about what to do when you convert a vector with too many or too few elements into an array. This example simply panics.

    Unfortunately, you currently can't parameterize over an array's length outside of the standard library. This means that each size would need to be a specialized implementation. In the future, something like this should work:

    #![feature(const_generics)]
    
    use std::convert::TryInto;
    
    fn demo<T, const N: usize>(v: Vec<T>) -> [T; N] {
        let boxed_slice = v.into_boxed_slice();
        let boxed_array: Box<[T; N]> = match boxed_slice.try_into() {
            Ok(ba) => ba,
            Err(o) => panic!("Expected a Vec of length {} but it was {}", N, o.len()),
        };
        *boxed_array
    }
    

    See also:

    • How to get a slice as an array in Rust?
    • How do I get an owned value out of a `Box`?
    • Is it possible to control the size of an array using the type parameter of a generic?
    0 讨论(0)
提交回复
热议问题