Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Make function argument mutable inside the function

  • mut

  • Sometimes you pass an argument and you would like to change that value inside the function (without chaning the external variable).

fn main() {
    let n = 1;
    println!("before: {n}");

    do_something(n);
    println!("after:  {n}");
}

fn do_something(mut val: i32) {
    println!("start:  {val}");
    val += 1;
    println!("end:    {val}");
}
before: 1
start:  1
end:    2
after:  1