Skip to content

What is going on in move_semantics1? #2039

Closed Answered by mo8it
tal-zvon asked this question in Q&A
Discussion options

You must be logged in to vote

let mut vec = vec uses shadowing. It doesn't clone anything on the heap. Here is an example that demonstrates this better:

let v1 = vec![1, 2];
let mut v2 = v1;
v2.push(3);
dbg!(v2);

This outputs v2 as [1, 2, 3]. But the important thing here is that v1 can't be accessed anymore. It was moved to v2, not cloned. So the following snippet won't compile:

let v1 = vec![1, 2];
let mut v2 = v1;
dbg!(v1); // Compiler error because v1 is moved to v2. 
v2.push(3);
dbg!(v2);

Now, if we change the two variable names to be the same:

let v = vec![1, 2];
let mut v = v;
v.push(3);
dbg!(v);

This code works too, but this time with shadowing.

If you own a value, you can also mutate it.

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@mo8it
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by mo8it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #637 on July 10, 2024 13:37.