rust-lang / rustlings

:crab: Small exercises to get you used to reading and writing Rust code!
https://rustlings.cool
MIT License
52.69k stars 10.02k forks source link

How does the solution for move_semantic3 work? #2060

Closed dataCobra closed 1 month ago

dataCobra commented 1 month ago

Hello,

I just completed move_semantics3.rs and was wondering how does the mut in front of a parameter work.

The variable vec0 is not mutable as a variable and also vectors don't have copy implemented.

How does the function make the given vec0 borrowed variable mutable?

I couldn't find an explanation and hope you can enlighten me.

Best regards dataCobra

ProdOrDev commented 1 month ago

Hello,

Adding mut in front of a function parameter makes the parameter (or more accurately variable) itself mutable within the function body, exactly like in a variable declaration.

So you can think of:

fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
    vec.push(88);

    vec
}

As:

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
    let mut vec = vec;
    vec.push(88);

    vec
}

Without the ability to add mut to function parameters you would have to manually shadow them if you wanted to modify them, using the let mut x = x pattern.

dataCobra commented 1 month ago

Thank you for the great explanation. :)

mo8it commented 1 month ago

Just adding something to the great answer by @ProdOrDev

How does the function make the given vec0 borrowed variable mutable?

vec0 is not borrowed here (not &Vec<i32> or &[i32]). It is moved (Vec<i32>). So the function owns the vector. If you own a value, you can also mutate it. If it is not declared as mutable, you can shadow it as @ProdOrDev explained.