How to mutate a borrowed value?

Hi,

I am fighting with the borrow checker to achieve something equivalent of the following C code.

#include <stdio.h>
int main(void) {
    int x = 5;
    int *y = &x;
    int invalid = 1;

    if (invalid == 1) {
        x = 7;
    }

    printf("%d %d", x, *y);
    return 0;
}

I am trying to do the same thing in Rust and can't get to compile it.

fn main() {
    let mut x = 5;
    let y = &x;

    let input = 1;

    if input == 1 {
        x = 7;
        y = &x;  // reference to the new value
    }

    println!("{} {}", x, *y);
}

I get compiler error E0506. I understand what the problem is but don't know how to fix it. I don't want to reference

Your C example does not use the y variable. The most straightforward translation would simply remove it. Beyond that, it is impossible to tell what the proper Rust translation would be until you provide a more complete C example because it really depends on what is going on with the y variable.

I would like to use the variable and the reference further too, possibly mutating them.

You can't. That's the whole point of Rust's Ownership and Borrowing system.

@jer I made a typo in the rust code, sorry for that. I don't want to access the old memory pointed by y. Instead I want to update the reference also to point to the new value and use both of them.

You cannot modify a value that is still borrowed. You likely have to reorganize your code to achieve your goal.
Maybe we can help better if you state what you are actually trying to do instead of you starting with a broken solution.

@jer I am working on this Instead of returning Response::network_error, I need to set response and internal_response which is a borrow of response to a new value when the condition matches.

At last, I got it to work :slight_smile: Thanks, guys!