-
Seems like there's a lot going on, and as a beginner, although I've read the majority of the Rust book, I'm a bit confused. First, a new immutable vector is declared - vec0. Inside fill_vec, you somehow try to convert the original immutable vector into a mutable one? Sure, you have ownership, but is that even possible? Can you convert an immutable variable into a mutable one after it's been declared? Or is it just declaring a completely new Am I close? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
related to #631 |
Beta Was this translation helpful? Give feedback.
-
I had a similar question about the hint in this exercise. It states:
Here is the function in question: fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(22);
vec.push(44);
vec.push(66);
vec
} Does it really get dropped at the end of the function? I was under the impression that ownership is transferred on assignment, so isn't it transferred to the shadow variable on the first line of the body? And then at the end of the function, isn't ownership transferred out? I'm confused by the hint stating it is dropped at the end of the function. |
Beta Was this translation helpful? Give feedback.
-
let v1 = vec![1, 2];
let mut v2 = v1;
v2.push(3);
dbg!(v2); This outputs 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. |
Beta Was this translation helpful? Give feedback.
let mut vec = vec
uses shadowing. It doesn't clone anything on the heap. Here is an example that demonstrates this better:This outputs
v2
as[1, 2, 3]
. But the important thing here is thatv1
can't be accessed anymore. It was moved tov2
, not cloned. So the following snippet won't compile:Now, if we change the two variable names to be the same:
This code works too, but this time with shadowing.
If you own a value, you can also mutate it.