Dereference then reference a reference to a number is allowed?

Is the code below ever allowed??
Did my compiler sleep and miss something :rofl:?


I use nightly version

fn main()
{
    let mut num1 = 1;
    let mut a = &mut num1;
    let mut b = &mut *a;
    *b = 4;
    println!("{}", a);
    *a = 3;
    println!("{}", a);
}

//Result:
//4
//3

Don't post pictures of code. That makes it harder to help you. Put the code in a code-block.

4 Likes

If it compiled then it is allowed.

In this case, the compiler can see that you only use the b reference once and then never touch it again. It figures out b is no longer alive after that and therefore you are allowed to use a again.

My question is, why do you think the compiler is wrong here?

1 Like

I just saw from the Rust ζ‰€ζœ‰ζƒ | θœιΈŸζ•™η¨‹ (runoob.com) that the mutable reference can't have multiple ones.
If I directly wirte below that

    let mut c = &mut num1;

The compiler will say that cannot borrow num1 as mutable more than once at a time E0499 second mutable borrow occurs here.

Wonder if there is any difference between the 2 references?

It's because b is a sub-reference of a. The reference a is disabled from the creation of b until the last use of b. This ensures that only one mutable reference is active at the time.

1 Like

But I can still use a below, is that normal?

It's after the last use of b, so it's ok.

1 Like

Thanks so much~~

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.