The error message you get from the compiler explains what the problem is:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:8:22
|
6 | fn new() -> Self {
| ---- return type is Data<'1>
7 | let p = Self {
8 | f: [&mut [1u8, 2u8], &mut [3u8, 4u8, 5u8]],
| ------^^^^^^^^^^-----------------------
| | |
| | creates a temporary value which is freed while still in use
| this usage requires that borrow lasts for `'1`
...
13 | }
| - temporary value is freed at the end of this statement
The arrays, such as [1u8, 2u8] are owned data. Creating such arrays and returning them would be fine. However, (mutable) references to these arrays, i.e. slices, are not something you can return from the function. This is because the owner of the array is a temporary variable in the new function, which is not accessible outside of that function.
Assuming you want to return a struct containing two arrays of integers, each of "any" length, you should use either a vector (which also allows resizing):
struct Data {
f: [Vec<u8>; 2],
}
impl Data {
fn new() -> Self {
let mut p = Self {
f: [vec![1u8, 2u8], vec![3u8, 4u8, 5u8]],
};
p.f[0][1] = 5;
p.f[1][2] = 7;
p
}
}
Or a box:
struct Data {
f: [Box<[u8]>; 2],
}
impl Data {
fn new() -> Self {
let mut p = Self {
f: [Box::new([1u8, 2u8]), Box::new([3u8, 4u8, 5u8])],
};
p.f[0][1] = 5;
p.f[1][2] = 7;
p
}
}
f: [Vec<u8>; 2]be the solution for instance?