Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...