Mutate integer passed in a function

Hey.

I know it is a very stupid question, but how do I mutate an int that I pass into function by reference? :smiley:

They are not kidding when they say rust has a tough learning curve..

Generally, you'll follow this kind of pattern:

fn main() {
    let mut my_int = 0;
    
    my_func(&mut my_int);

    println!("my_int is now: {}", my_int);
}

fn my_func(some_integer: &mut usize) {
    *some_integer += 1;
}

Note how I must say *some_integer. I'm not actually dereferencing and taking from anywhere, it's closer to me referring to the place which some_integer points to.

2 Likes

This is the pattern for all basic types, right?

Yes, it works for any type, since the &mut reference gives you mutable (AKA exclusive) access to the object.

Well how did you try learning this basic thing?

(Not everybody says that btw – coming from C++, Rust had basically no learning curve for me.)

No, they are not kidding when they say Rust has a tough learning curve.

However the problem you give there is not an example of that. For example if one were to write such a thing in C it might look like:

#include <stdio.h>

void my_func(int* some_integer) {
    *some_integer += 1;
}

int main(int argc, char* argv[]) {
    int my_int = 0;

    my_func(&my_int);

    printf("my_int is now: %d\n", my_int);

    return 0;
}

Which I would posit is even more complex. I don't hear people shouting that C is hard to learn.
It would look much the same in C++.

How would one do such a pass by reference in Python? I never did figure that out.

Much in the same way except you are forced to do heap allocation for it (for all I know). Since in Python, classes are implicitly and obligatorily pointers, you can wrap the object in question in a data structure of some sort, and dereference through the data structure by indexing or method calling:

def change_value(box):
    box[0] = 37

x_box = [13]
change_value(x_box)
print(x_box[0]) # 37