[doubt]: Permissions in the unsafe-program-copying-vs-moving-out-of-a-collection example from the Rust book #130
-
DescriptionIn this example from the Rust book. It shows that the vector When I try to print out/read fn main() {
let v: Vec<i32> = vec![0, 1, 2];
let n_ref: &i32 = &v[0];
println!("{:?}", v);
let n: i32 = *n_ref;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Thanks for the question and sorry for the delayed response. The difference between the first and second code examples you've provided is that the print statement extends the liveness of In the second piece of code, where you inserted the print statement, the compiler determined that The real problem is that our diagrams [currently] only show one icon per set of permissions changes. But in the first image there are two changes on line 3, (1) the path is borrowed, and (2) the path is no longer used. As you can see in my above image, when a path is no longer used we use the down arrow to represent this. Ideally we could include both the down arrow and right arrow on line 3 of your example to say "path is borrowed here and path is no longer used." This is a known confusion. We even have an open issue, #85, that will hopefully get resolved in the future. |
Beta Was this translation helpful? Give feedback.
Thanks for the question and sorry for the delayed response.
The difference between the first and second code examples you've provided is that the print statement extends the liveness of
v
. The Rust compiler is smart, so smart, that in your first image it says "hey,v
is no longer used in this function so we can declarev
dead after line 3." (If you're curious, the compiler uses something called a liveness analysis to figure this out.) As a result, the compiler will also remove permissions to that path.In the second piece of code, where you inserted the print statement, the compiler determined that
v
was live for a little longer and that's why the read permissions (R
) are retained. In an …