Redefining a moved var

Hello all

I'm trying to process something and then return the processed something, and do this several times. But rust doesnt allow me to let a new var to hold the processed stuff. Here is a little code to illustrate the idea

Thanks a lot in advance

fn main() {
    let list = vec![10, 40, 30];

    loop {
        let (changes, list) = process(list);
        if changes == 0 {
            break;
        }
    }
}

fn process(a: Vec<u32>) -> (usize, Vec<u32>) {
    let mut b = a.clone();
    let _ = b.pop();
    (b.len(), b)
}

(Playground)

let defines a new binding (shadowing any previous variable if it existed with the same name), and it doesn't overwrite the same variable. For that, you need assignment.

    let mut list = vec![10, 40, 30];

    loop {
        let (changes, newlist) = process(list);
        list = newlist;

        if changes == 0 {
            break;
        }
    }

Essentially, you'll need to understand the compiler's representation of bindings. Binding names do NOT uniquely identify locations by themselves. You also have to consider the scope. A given name always refers to the identically-named binding in the innermost scope, but that's a completely separate variable, and let always creates a new one, it never mutates.

It's like saying that you want John Doe in New York to send you money, changing the state of his wallet. That doesn't help though if you recently met another John Doe in San Francisco, who hasn't got a cent in his wallet. You'll not be able to get money from him, even though you might have updated your phone's contact list to point to the John Doe in SF – he still doesn't magically have all the money of the NYC-based Joe, they are different persons in different places but with the same name.

1 Like

In a future version of rust, another alternative way to write this will be

let mut list = vec![10, 40, 30];

loop {
    let changes;
    (changes, list) = process(list);
    if changes == 0 {
        break;
    }
}
1 Like

Awesome. Much clearer now!

Thanks a lot for your support

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.