0

I want to create a type containing an array allocated to the stack.

struct MyStruct {
    values: [u8; 25],
}

I'm not able to implement the MyStruct::new() trait to initialize the struct's array.

Here's my unsuccessful atempt:

impl MyStruct {
    fn new(numbers: &[u8]) -> Self  {
        Self  {
            values: numbers.copy_from_slice(),
        }
    }
}

I encountered some solutions on the internet, but they all either initialize the array to 0 or use the heap with Vec<u8>.

I can't find anything on the internet other than "use a vector" solutions.
How do I memcpy arrays in a safe way in rust?

gberth
  • 467
  • 5
  • 13
  • Does this answer your question? [How to get a slice as an array in Rust?](https://stackoverflow.com/questions/25428920/how-to-get-a-slice-as-an-array-in-rust) You'd do `numbers.try_into().unwrap()` with potentially handling the error properly in case the slice has more or fewer elements than the array requires. – kmdreko Dec 06 '21 at 23:34
  • @kmdreko it does. Thanks a lot for your help. – gberth Dec 06 '21 at 23:39

0 Answers0