How to pass the ownership of a large size array?

Hi, I learned that types and structs in Rust have moving semantics by default unless they implement the "Copy" trait. I read in the documentation that a [T; N] array, which has a static size (and allocated on the stack?), also implements Copy. But when I have a large size array, say [f64;10000], will this array still be passed by copy by default? If I want to avoid copying so much data in this array, I can pass by reference. But if I want to modify this array and avoid some limitations of mutable reference, can I pass the ownership of this array?

Yes. If you're lucky it may optimize out but it's not guaranteed.

You can make a Box<[_; N]>. If it's very large, you may have to take care to avoid the stack when constructing it (Rust doesn't have guaranteed emplacement).

2 Likes

If you do need to construct it, Box::<[_; N]>::try_from(vec![0; N]).unwrap() is your friend.

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