Search code examples
rustmutable

mutability requirement in rust after a function call


Why would mut not be required here

#[allow(dead_code)]
fn addo2(v: Vec<u64>, oi: Option<u64>) -> Vec<u64> {
    oi.into_iter().fold(v, |mut v, i| add(v, i)) //warning: variable does not need to be mutable
}

#[allow(dead_code)]
fn add(mut v: Vec<u64>, i: u64) -> Vec<u64> {
    v.push(i);
    v
}

when it is, as expected, required in this code

fn addo(v: Vec<u64>, oi: Option<u64>) -> Vec<u64> {
    oi.into_iter().fold(v, |mut v, i| {
        v.push(i);
        v
    })
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=097bb3c3cd5c8cd7aa69c5bfafd177fc


Solution

  • The difference between v.push(i); v and add(v, i) is that the former modifies v in-place, whereas the latter passes v into add, and receives a (possibly unrelated) value back. mut refers to modifying something you own, so it doesn't apply when passing ownership to someone else.