Is possible change variable inside in `change` function ? and why?

fn main() {
    let i = 0i64;
    change();
    assert_eq!(i, 1);
}


fn change() {
    /// code here
}

here is the code

No, it's not possible. Functions don't have the ability to reach outside of their scope and touch variables elsewhere. If you instead provide the function with a mutable reference to your value, you can totally change it then:

fn main() {
    let mut x = 0;
    change(&mut x);
    assert_eq!(x, 1);
}

fn change(val: &mut usize) {
    *val += 1;
}
8 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.