Initialize a variable in a loop

I don't understand how to initialize parts.path_and_query inside my loop. My goal is to generate multiple paths during every iteration and push the complete URL to the vector. There is a borrowing problem and I don't really understand this error for that special case.

assign to part of moved value: `parts`
value partially assigned here after move
move occurs because `parts` has type `Parts`, 
which does not implement the `Copy` trait
pub fn generate_user_uuid(students_num: i32) -> Vec<Uri> {
    let mut parts: Parts = Parts::default();
    let mut uris: Vec<Uri> = Vec::new();

    parts.scheme = Some("http".parse().unwrap());
    parts.authority = Some("".parse().unwrap());

    let mut i: i32 = 0;

    while i < students_num {
        parts.path_and_query = Some("/foo?uuid=".parse().unwrap());
        let uri: Uri = Uri::from_parts(parts).unwrap();
        i += 1;

It's just what the error message says. If you move out of the variable during one iteration of the loop, it will be invalidated, so the next iteration wouldn't make sense. You need to clone the URL.

It's an ownership problem -- Parts doesn't implement Copy or even Clone, so you're going to have to create a fresh one each time through the loop.

Here's one way.

1 Like

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.