How to mutate a borrowed value?


#1

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


#2

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.


#3

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


#4

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


#6

@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.


#7

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.


#8

@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.


#9

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