Because I am developing an MLops framework that supports multiple types of database as backend and allows users to customize some fields. As the number of these fields is unknown at compiling time, I can only represent them using a vec. However, a trait method for one of the databases needs to be called frequently when inserting data, and its signature only supports using an array type. The solution provided for this question offers a good approach, but I believe it still involves memory allocation on the heap, which may not be fast enough for frequent data insertion in such a scenario and could slow down the users' entire application .
Suppose there's a vector of certain type with known size:
let vec = vec![1, 2, 3, 4];
How can we turn it into an array?
The method is expected to have minimal memory overhead, without any unnecessary clone operations or operations on the heap, etc.
I've tried this solution:
fn vec_to_array(vec: Vec<i32>) -> [i32; 4] {
let boxed_slice = vec.into_boxed_slice();
let ptr = Box::into_raw(boxed_slice) as *mut i32;
unsafe { std::ptr::read(ptr); }
}
However, it appears to have poor performance since it requires memory allocation on the heap.