Skip to content

How does the solution for move_semantic3 work? #2061

Closed Answered by ProdOrDev
dataCobra asked this question in Q&A
Discussion options

You must be logged in to vote

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.

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by mo8it
Comment options

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

Comment options

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

This discussion was converted from issue #2060 on July 30, 2024 10:04.