I want to initialize an array of self defined structs automatically with a given rule.
With primitive types and types that implement Copy
, I would do something like let x: [u8; 5] = [0; 5];
, but with a type which can't derive Copy
I have to do something else.
I probably could write down the whole list, but that is quite inconvenient, especially if I just want dummy values which will be altered later, equivalent to initializing an integer array with zeros.
I have tried a for
loop like this
use std::collections::LinkedList;
enum CourseType {
Dummy1,
Dummy2,
}
struct Week {
number: u64,
days: [Day; 5], //Mo-Fr
}
struct Day {
courses: LinkedList<Course>, // LinkedList prevents Copy
}
struct Course {
beginning: u8,
courseType: CourseType,
}
fn get_weeks() -> Option<Vec<Week>> {
let mut weeks = Vec::with_capacity(20);
for i in 1..14 {
let week = Week {
number: i,
days: {
let mut ret: [Day; 5]; // definition of the array
for i in 0..4 {
// loop to initialize
ret[i] = Day {
courses: LinkedList::new(),
} //error[E0381]
}
ret //error[E0381]
},
};
weeks.push(week);
}
Some(weeks)
}
As commented in the snippet, I get an error[E0381] by "initializing" this way:
error[E0381]: use of possibly uninitialized variable: `ret`
--> src/main.rs:31:21
|
31 | / ret[i] = Day {
32 | | courses: LinkedList::new(),
33 | | }
| |_____________________^ use of possibly uninitialized `ret`
error[E0381]: use of possibly uninitialized variable: `ret`
--> src/main.rs:35:17
|
35 | ret
| ^^^ use of possibly uninitialized `ret`
How would I initialize an array of this kind?
I have a fixed size of data in this case, since the (work)week only has 5 days. Using a dynamic type, like a vector, seems to be imprecise. I tried tuples before, but there I had a comparable problem where I had to iterate through the tuple indices. It seemed impossible (with variables) to address the index with a variable (something like tuple.index
instead of e.g tuple.3
).
Maybe I have to use some kind of a slice (&[Day; 5]
) instead of an array, but I guess my understanding of Rust isn't quite there yet.