Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

rust - Why does creating a mutable reference to a dereferenced mutable reference work?

I understand you're not allowed to create two mutable references to an object at once in Rust. I don't entirely understand why the following code works:

fn main() {
    let mut string = String::from("test");
    let mutable_reference: &mut String = &mut string;
    mutable_reference.push_str(" test");
    // as I understand it, this creates a new mutable reference (2nd?)
    test(&mut *mutable_reference);

    println!("{}", mutable_reference);
}

fn test(s: &mut String) {
    s.push_str(" test");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The rule

There shall only be one usable mutable reference to a particular value at any point in time.

This is NOT a spatial exclusion (there CAN be multiple references to the same piece) but a temporal exclusion.

The mechanism

In order to enforce this, &mut T is NOT Copy; therefore calling:

test(mutable_reference);

should move the reference into test.

Actually doing this would make it unusable later on and not be very ergonomic, so the Rust compiler inserts an automatic reborrowing, much like you did yourself:

test(&mut *mutable_reference);

You can force the move if you wanted to:

test({ let x = mutable_reference; x });

The effect

Re-borrowing is, in essence, just borrowing:

  • mutable_reference is borrowed for as long as the unnamed temporary mutable reference exists (or anything that borrows from it),
  • the unnamed temporary mutable reference is moved into test,
  • at the of expression, the unnamed temporary mutable reference is destroyed, and therefore the borrow of mutable_reference ends.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...