Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

What is going on in move_semantics1? #637

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tal-zvon opened this issue Feb 2, 2021 · 2 comments
Closed

What is going on in move_semantics1? #637

tal-zvon opened this issue Feb 2, 2021 · 2 comments

Comments

@tal-zvon
Copy link
Contributor

tal-zvon commented Feb 2, 2021

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.
Then on the next line, you pass ownership of vec0 to the fill_vec function. Simple enough.

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 vec variable inside the fill_vec function that happens to have the same name (shadows) the original, and sets its value to the value of the original (a blank vector), thereby cloning it in the heap? I guess since the function now owns the original, as soon as the function returns, it gets dropped (or is it dropped as soon as it gets shadowed?), and the memory gets de-allocated, leaving only the new vector that is returned by the function?

Am I close?

@fraterenz
Copy link

related to #631

@pkazmier
Copy link

pkazmier commented Mar 4, 2021

I had a similar question about the hint in this exercise. It states:

So vec0 is being moved into the function fill_vec when we call it on line 10, which means it gets dropped at the end of fill_vec, which means we can't use vec0 again on line 13

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.

@rust-lang rust-lang locked and limited conversation to collaborators Jul 10, 2024
@mo8it mo8it converted this issue into discussion #2039 Jul 10, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants