Confusion about 'Variable bindings'

fn main() {
    let v = vec![1, 2, 3];
    let v2 = v;
    let v = v2;   //this line is ok.


In other language, such as “C”, such code can cause a redefinition error.
like this,

int main() {
    int a = 10;
    int b = a;
    int a = b;
    return 0;

Dos the Rust permits ‘redefinition’ of a variable? are there really two ‘v’ on stack? or let v = v2 just return the ownersip back to ’ v ’ and there is one ’ v ’ ?


This is called “shadowing”.

Semantically speaking, the Vec struct on the stack (pointer, length capacity, NOT the data) get copied twice. LLVM should optimize this entire program to a noop though.

With Copy types, like integers, the older info is still there, but cannot be accessed, as the new name replaces the old name.


Thank you for your reply,which is very useful to me.


in the C-lang/ we also got “shadowing” :

int i = 45;
printf("%d\n", i); //prints 45
int i = 50; //inner i shadows outer i
printf("%d\n", i); //prints 50
printf("%d\n", i); //prints 45