Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Structs and circural references

  • Rust will make sure we cannot create circular reference in this way.
  • #[allow(unused_mut)] is needed to silence clippy, the linter
fn main() {
    let mut joe = Person {
        name: String::from("Joe"),
        partner: None,
    };
    #[allow(unused_mut)]
    let mut jane = Person {
        name: String::from("Jane"),
        partner: None,
    };
    println!("{:?}", &joe);
    println!("{:?}", &jane);
    joe.partner = Some(&jane);
    //jane.partner = Some(&joe);
    println!("{:?}", &joe);
    println!("{:?}", &jane);
}

#[derive(Debug)]
#[allow(dead_code)]
struct Person<'a> {
    name: String,
    partner: Option<&'a Person<'a>>,
}

  • Try to enable the commented out code and see the error message.
error[E0506]: cannot assign to `jane.partner` because it is borrowed
 --> src/main.rs:8:5
  |
7 |     joe.partner = Some(&jane);
  |                        ----- `jane.partner` is borrowed here
8 |     jane.partner = Some(&joe);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^ `jane.partner` is assigned to here but it was already borrowed
9 |     dbg!(&joe);
  |          ---- borrow later used here

For more information about this error, try `rustc --explain E0506`.
error: could not compile `circural-references` (bin "circural-references") due to previous error