Conversion between Vec<[T; N]> and Vec<T>?

Of course. So using this method will not always be zero cost. That said, I do feel it is unlikely for this to be much of a problem in circumstances like constructing an ndarray; typically these can be constructed with with_capacity.

(I'll note that, to my memory, conversion into a boxed slice always calls reallocate, but this function is allowed to return the same pointer)


(Originally this post said something like "you'd have to delete items from the vec," which was wrong; if you push items into the vec beyond capacity then this only works if there happens to be a confluence between Vec's growth strategy and the allocator's accepted sizes)

No in my case it never needs to grow or shrink or even change. Which is the reason that I could use an ArrayView which is immutable. And yes I do use with_capacity so there shouldn't be a reallocation if I could do it the Box way. But for me the slice conversion was enough.

The function aview2 already does this.. :slight_smile: And coming const generics fixes will make it more general (for all array sizes).

Playground link

use ndarray::aview2;

fn main() {
    let vec: Vec<[f64; 3]> = vec![[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]];

    let array = aview2(&vec);
    println!("{:8.4}", array);
    // [[  0.0000,   1.0000,   2.0000],
    //  [  3.0000,   4.0000,   5.0000]]

}
1 Like

In some places this works very well for me but at other places in my code I still need to use slice conversion method because of the const generics. Thanks!

std can (and maybe should) provide <[[T; N]]>::flatten(&self) -> &[T]. The fun part is that we would probably also want to add <[[T; N]; M]>::flatten(self) -> [T; N*M] and/or <[[T; N]; M]>::flatten(&self) -> &[T; N*M] at the same time to avoid autoref making it difficult to add (one or both of) those in the future, the same way impl IntoIterator for [T; N] has been difficult to add "quietly."

After slice flatten is available, it's reasonable for std to add <Vec<[T; N]>>::flatten(this: Self) -> Vec<T>, even if it's still not directly allowed for user code to open code it with from_raw_parts (due to the difficulty of spec'ing it to allow this cleanly).

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.