I am trying to find an elegant way to fill a vector of struct elements with a loop or logic instead of writing one .push() for every element I create.
The struct element is a question with many more fields than in the following example and the instances need to be mutable because they are modified by user input :
struct Question {
id: usize,
question: String,
}
fn main() {
//A large and growing list of questions
let mut q0 = Question {
id: 0,
question: String::from("A field I fill in manually"),
};
// .
// .
// .
let mut q100 = Question {
id: 100,
question: String::from("Another field, each one is different"),
};
let total_questions: usize = 100;
let mut w: Vec<String> = Vec::new();
for a in 0..total_questions {
let s = format!("q{}", a);
w.push(s);
}
//w contains ["q0", "q1", ..., "q100"] but is of type std::string::String
let mut v: Vec<&mut Question> = Vec::new();
//Expects type struct `main::Question`
//I would like to avoid :
v.push(&mut q0);
v.push(&mut q1);
// .
// .
// .
v.push(&mut q100);
}
I am not sure that in my example the w: Vec<String> is of any use.
I have looked into .collect() but could not understand how to utilize it in my case.
I'd be happy to be pointed towards a similar question if this is a duplicate I have not found one.
Edit : I have changed the structs string content as it was misleading. They each contain Strings that are unique and cannot be generated. I also realized that Stack Overflow automatically included this in a some_fn() function when we are actually inside main()
Questionstructs are produced ?vbe aVec<&mut Question>with references to local variables? Why not justVec<Question>?Vec<&mut Question>. This complicates things because something has to own theQuestions. What's wrong with justVec<Question>?Questionstructs without hardcoding. You can use json format(load external JSON file or embed as JSON string) then deserialize asVec<Question>. If you still want to write as hardcoded then you can create your struct with a constructor, you can push the question while it constructs like this